【问题标题】:Convert an array into an ArrayList [duplicate]将数组转换为 ArrayList [重复]
【发布时间】:2012-04-06 08:43:59
【问题描述】:

在 Java 中将数组转换为 ArrayList 时遇到了很多麻烦。这是我现在的数组:

Card[] hand = new Card[2];

"hand" 包含一个 "Cards" 数组。这是ArrayList 的样子?

【问题讨论】:

标签: java arrays list arraylist blackjack


【解决方案1】:

作为ArrayList,该行将是

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

要使用ArrayList,您必须这样做

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

另请阅读http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

【讨论】:

  • 谢谢!最后一个快速问题..我如何接受一个数组列表到一个方法中?现在我有: public void getHandValue(ArrayList hand) {...} 数组列表在我的主要参数中。只是“ArrayList”这个词出现了错误。
  • 你应该能够有一个方法签名void getHandValue(ArrayList&lt;Card&gt; hand) 当你调用该方法时问题很可能发生。
【解决方案2】:

声明列表(并使用空数组列表对其进行初始化)

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

添加元素:

Card card;
cardList.add(card);

迭代元素:

for(Card card : cardList){
    System.out.println(card);
}

【讨论】:

    【解决方案3】:

    这会给你一个列表。

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

    如果你想要一个数组列表,你可以这样做

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

    【讨论】:

    • 不!这提供了一个对象,该对象充当底层对象的List 包装器。与真正的ArrayList 不同,生成的List 不可调整大小,尝试将.add 元素添加到其末尾将导致UnsupportedOperationException
    【解决方案4】:
    List<Card> list = new ArrayList<Card>(Arrays.asList(hand));
    

    【讨论】:

      猜你喜欢
      • 2017-04-10
      • 2012-05-18
      • 2014-04-30
      • 2012-10-04
      • 2020-09-10
      • 1970-01-01
      • 2011-12-09
      • 2012-05-03
      • 2016-06-12
      相关资源
      最近更新 更多