Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an array into an ArrayList [duplicate]

I'm having a lot of trouble turning an array into an ArrayList in Java. This is my array right now:

Card[] hand = new Card[2];

"hand" holds an array of "Cards". How this would look like as an ArrayList?

like image 856
Saatana Avatar asked Mar 21 '12 19:03

Saatana


People also ask

How do you duplicate an ArrayList?

ArrayList cloned = new ArrayList(collection c); where c is the collection containing elements to be added to this list. Approach: Create a list to be cloned. Clone the list by passing the original list as the parameter of the copy constructor of ArrayList.

Can ArrayList have duplicate?

ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.

Can ArrayList have duplicate values in Java?

A better way (both time complexity and ease of implementation wise) is to remove duplicates from an ArrayList is to convert it into a Set that does not allow duplicates. Hence LinkedHashSet is the best option available as this do not allows duplicates as well it preserves the insertion order.


4 Answers

This will give you a list.

List<Card> cardsList = Arrays.asList(hand); 

If you want an arraylist, you can do

ArrayList<Card> cardsList = new ArrayList<Card>(Arrays.asList(hand)); 
like image 186
Kal Avatar answered Sep 28 '22 04:09

Kal


As an ArrayList that line would be

import java.util.ArrayList; ... ArrayList<Card> hand = new ArrayList<Card>(); 

To use the ArrayList you have do

hand.get(i); //gets the element at position i  hand.add(obj); //adds the obj to the end of the list hand.remove(i); //removes the element at position i hand.add(i, obj); //adds the obj at the specified index hand.set(i, obj); //overwrites the object at i with the new obj 

Also read this http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

like image 42
twain249 Avatar answered Sep 28 '22 04:09

twain249


List<Card> list = new ArrayList<Card>(Arrays.asList(hand));
like image 29
Eng.Fouad Avatar answered Sep 28 '22 05:09

Eng.Fouad


declaring the list (and initializing it with an empty arraylist)

List<Card> cardList = new ArrayList<Card>();

adding an element:

Card card;
cardList.add(card);

iterating over elements:

for(Card card : cardList){
    System.out.println(card);
}
like image 43
bpgergo Avatar answered Sep 28 '22 05:09

bpgergo