【问题标题】:Get array item from arraylist从arraylist获取数组项
【发布时间】:2015-12-24 06:49:01
【问题描述】:

我正在修改我的问题以使其更易于理解。 我有以下数组列表

ArrayList<AnotherClass> exmapleName = new ArrayList<AnotherClass>();
// AnotherClass is a class I created, I store objects of the class in this array, the code to this doesn't matter this works.

在exampleName里面我有不同类型的数据

public AnotherClass (String someString,  int someInt, int anotherInt, int[] intArray, ArrayList<Integer> arrayList)
//Header of the constructor

现在我需要做的是访问和存储arrayList[0]。但是一旦创建了对象,我就需要这样做,所以arrayList里面实际上有一些东西。

这是我尝试过但似乎不起作用的方法

         AnotherClass test1 = exampleName.get(1);
        ArrayList<Integer> test2 = test1.arrayList;
        int test3 = test2.arrayList[0];
// I broke it down into separate lines to make it more understandable 

编译错误如下

cannot find symbol
                    int test3 = test2.arrayList[0];
symbol:   variable arrayList
location: variable test2 of type ArrayList<Integer>

1 个错误

【问题讨论】:

  • 你有一个 int[] 的 ArrayList?这是你的类型的数据。@Blueaddiction

标签: java arrays arraylist


【解决方案1】:

如果你有一个“普通”数组,你可以简单地访问i-th 元素,索引为myArrayList.get(1).normalArray[i]

如果您需要处理数组,请考虑将其存储到本地副本并从中访问。

int[] numbers = myArrayList.get(1);
for(Integer num : numbers){
  // Process the numbers array.
  System.out.print(num);
}

【讨论】:

  • 我以前试过这个,但是我需要将变量存储为一个 int 但它需要一个整数数组 R.java:70: error: array required, but ArrayList found
  • @Blueaddiction 所以你是说normalArray 被声明为ArrayList&lt;Integer&gt;?你原来的帖子里没这么说。您说的是其他人都误解的“int array”。请向我们展示更多代码。
  • 我说主数组是一个整数数组列表,里面有一个整数数组。我会在休息时再发布一些代码
  • 我已经修改了主帖以更清楚地反映问题
【解决方案2】:
 int arr[] = myArrayList.get(1);

访问喜欢,

int first=arr[0];

【讨论】:

  • 其实等它没用,错误:不兼容类型://我的其他类-->(anotherClass) 无法转换为int[] int[] test1 = eQuestion.get(1);
  • 能否请您发布更多代码,以便我确定它是否仍然不适合您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-25
  • 2023-04-09
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多