Need help with ArrayList. Not exactly sure why i cant make it work once i put it into a class and instantiate an object. | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 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)); } }

13th Mar 2018, 2:51 PM
Stefan Kef
Stefan Kef - avatar
4 ответов
+ 11
thanks, works now. I didn't even realize I had to use the add method in the constructor.
13th Mar 2018, 3:50 PM
Stefan Kef
Stefan Kef - avatar
+ 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); } }
13th Mar 2018, 3:43 PM
Geo
Geo - avatar
+ 4
you are welcome.
13th Mar 2018, 3:51 PM
Geo
Geo - avatar
+ 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.
11th Apr 2018, 12:31 AM
Luther Conley