在java中int数组中的ArrayList [英] ArrayList of int array in java

查看:184
本文介绍了在java中int数组中的ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的ArrayList的概念。我不得不做一些行程序code为:

 的ArrayList< INT [] GT; ARL =新的ArrayList< INT []>();
INT A1 [] = {1,2,3};
arl.add(0,A1);
的System.out.println(ArrayList包含:+ arl.get(0));

它给人的输出: ArrayList包含:[I @ 3e25a5

现在我的问题是:


  1. 如何显示正确的值,即1 2 3。

  2. 我如何可以访问阵列A1即的一个元素,如果我想知道在A1中的值[1]。


解决方案

首先,初始化一个容器,你不能使用基本类型(即 INT ;你可以使用 INT [] ,但只要你想只是一个整数数组,我看到没有使用)。相反,你应该使用整数,如下:

 的ArrayList<整数GT; ARL =新的ArrayList<整数GT;();

有关添加元素,只需用添加功能:

  arl.add(1);
arl.add(22);
arl.add(-2);

最后,但并非最不重要的,用于打印的ArrayList 您可以使用内置的功能的toString()

 的System.out.println(ArrayList包含:+ arl.toString());

如果您要访问的元素,其中是从0到阵列-1的长度的指数,你可以做:

  INT I = 0; //索引0是第一个元素的
的System.out.println(第一个元素是:+ arl.get(I));

我建议先阅读Java的集装箱,开始与他们合作之前。

I'm new to the concept of arraylist. I had make a few line program code as:

ArrayList<int[]> arl=new ArrayList<int[]>();
int a1[]={1,2,3};
arl.add(0,a1);
System.out.println("Arraylist contains:"+arl.get(0));

It gives the output: Arraylist contains:[I@3e25a5

Now my questions are:

  1. How to display the correct value i.e. 1 2 3.
  2. How can I access the single element of array a1 i.e. if I want to know the value at a1[1].

解决方案

First of all, for initializing a container you cannot use a primitive type (i.e. int; you can use int[] but as you want just an array of integers, I see no use in that). Instead, you should use Integer, as follows:

ArrayList<Integer> arl = new ArrayList<Integer>();

For adding elements, just use the add function:

arl.add(1);  
arl.add(22);
arl.add(-2);

Last, but not least, for printing the ArrayList you may use the build-in functionality of toString():

System.out.println("Arraylist contains: " + arl.toString());  

If you want to access the i element, where i is an index from 0 to the length of the array-1, you can do a :

int i = 0; // Index 0 is of the first element
System.out.println("The first element is: " + arl.get(i));

I suggest reading first on Java Containers, before starting to work with them.

这篇关于在java中int数组中的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆