+ 9
Need help with ArrayList. Not exactly sure why i cant make it work once i put it into a class and instantiate an object.
//my code minus an arraylist so it fits here import java.util.*; class Deck{ ArrayList<String> suit =new ArrayList<String>(); suit.add("Spades"); suit.add("Clubs"); suit.add("Hearts"); suit.add("Diamonds"); public String getSuit(int index){ return suit.get(index); } } public class Program { public static void main(String[] args) { Deck primary= new Deck(); System.out.println(primary.getSuit(0)); } }
4 Answers
+ 11
thanks, works now. I didn't even realize I had to use the add method in the constructor.
+ 5
Your class Deck is not well written.
You forget the constructor.
class Deck{
List<String> suit =new ArrayList<>();
// Constructor
public Deck() {
suit.add("Spades");
suit.add("Clubs");
suit.add("Hearts");
suit.add("Diamonds");
}
public String getSuit(int index){
return suit.get(index);
}
}
+ 4
you are welcome.
+ 2
The Java API provides special classes to store and manipulate groups of objects.
One such class is the ArrayList. Standard Java arrays are of a fixed length, which means that after they are created, they cannot expand or shrink.
On the other hand, ArrayLists are created with an initial size, but when this size is exceeded, the collection is automatically enlarged.
When objects are removed, the ArrayList may shrink in size. Note that the ArrayList class is in the java.util package, so it's necessary to import it before using it.
Create an ArrayList as you would any object.