Java Reference
In-Depth Information
You can use the static shuffle method in the java.util.Collections class to perform
a random shuffle for the elements in a list. Here are examples:
shuffle method
Integer[] array = { 3 , 5 , 95 , 4 , 15 , 34 , 3 , 6 , 5 };
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(array));
java.util.Collections.shuffle(list);
System.out.println(list);
11.35 Correct errors in the following statements:
Check
Point
int [] array = { 3 , 5 , 95 , 4 , 15 , 34 , 3 , 6 , 5 };
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(array));
11.36 Correct errors in the following statements:
int [] array = { 3 , 5 , 95 , 4 , 15 , 34 , 3 , 6 , 5 };
System.out.println(java.util.Collections.max(array));
11.13 Case Study: A Custom Stack Class
This section designs a stack class for holding objects.
Key
Point
Section 10.6 presented a stack class for storing int values. This section introduces a stack class
to store objects. You can use an ArrayList to implement Stack , as shown in Listing 11.10.
The UML diagram for the class is shown in Figure 11.4.
VideoNote
The MyStack class
MyStack
-list: ArrayList<Object>
A list to store elements.
+isEmpty(): boolean
+getSize(): int
+peek(): Object
+pop(): Object
+push(o: Object): void
Returns true if this stack is empty.
Returns the number of elements in this stack.
Returns the top element in this stack without removing it.
Returns and removes the top element in this stack.
Adds a new element to the top of this stack.
F IGURE 11.4
The MyStack class encapsulates the stack storage and provides the operations
for manipulating the stack.
L ISTING 11.10
MyStack.java
1 import java.util.ArrayList;
2
3 public class MyStack {
4
private ArrayList<Object> list = new ArrayList<>();
array list
5
6
public boolean isEmpty() {
stack empty?
7
return list.isEmpty();
8 }
9
10
public int getSize() {
get stack size
11
return list.size();
12 }
13
14
public Object peek() {
peek stack
15
return list.get(getSize() - 1 );
16 }
 
 
 
Search WWH ::




Custom Search