ArrayList ar = new ArrayList(); ar.add("字符串"); ar.add(new MyHellowWord()); ar.add(Float.valueOf("10.25")); ar.add(Integer.valueOf("10")); ar.add(Boolean.valueOf(true));
我刚接触java,不太懂,请问使用ar.add()时,可以不使用index吗?谢谢
ArrayList中的元素不能是基本类型的变量通过对应的wrap类封装之后再放入arrayList中ArrayList a = new ArrayList(); a.add( new Integer(5) ); a.add( new Character('c') );
取的时候有什么难的?ArrayList就是一动态数组
ar.add(new MyHellowWord());我不懂。
public boolean add(Object o) Appends the specified element to the end of this list. Specified by: add in interface List Overrides: add in class AbstractList Parameters: o - element to be appended to this list. Returns: true (as per the general contract of Collection.add). 这是这个方法的说明。只要是一个Object就可以加到ArrayList中去。
放的时候add就行了,取出来的时候强制转换一下ok了
取出来是Object型,再强制转换一下。
取出来的时候最好用一下RTTI,这样的话可以知道是什么类型的
ar.add(new MyHellowWord());我不懂。往ar里面放一个 MyHellowWord类的对象。我刚接触java,不太懂,请问使用ar.add()时,可以不使用index吗?谢谢add()的时候,根据add的先后顺序依次加在ArrayList对象里,你可以把 ArrayList看做一个动态数组,定义的时候不用指明其大小,里面只能存放对象,不能存 像int,float,double等primitive type
现在JAVA 5。0对泛型的支持用在ARRAYLIST里很方便。相当于不限制大小的数组。 ArrayList<Double> a = new ArrayList<Double>();
ArrayList类是一个实现了Collection接口的类ArrayList是Java语言中提供的一种高级的数据结构,可以保存一系列的对象,Java不支持动态数组,ArrayList提供了一种与“动态数组”相近的功能。如果我们不能预先确定要保存的对象的数目,或是需要方便获得一个对象的存放位置,可以用ArrayList或Vecotr。ArrayList中保存的是对象,而不是基本数据类型的数据,比如说我们不能在其中定义int类型的基本数据,而是要使用其包装类Integer。下面一个例子说明了ArrayList的用法,并用Iterator接口取出其中的保存的对象。import java.util.*; public class TestCollection { public static void main(String [] args) { ArrayList a1=new ArrayList(); a1.add(new Integer(10)); a1.add(new Integer(2)); Iterator itr=a1.iterator(); int sum=0; while(itr.hasNext()) { Integer intObj=(Integer)itr.next(); sum=sum+intObj.intValue(); } System.out.println(sum); } }
ar.add("字符串");
ar.add(new MyHellowWord());
ar.add(Float.valueOf("10.25"));
ar.add(Integer.valueOf("10"));
ar.add(Boolean.valueOf(true));
ArrayList中的元素不能是基本类型的变量通过对应的wrap类封装之后再放入arrayList中ArrayList a = new ArrayList();
a.add( new Integer(5) );
a.add( new Character('c') );
取的时候有什么难的?ArrayList就是一动态数组
Appends the specified element to the end of this list. Specified by:
add in interface List
Overrides:
add in class AbstractList
Parameters:
o - element to be appended to this list.
Returns:
true (as per the general contract of Collection.add).
这是这个方法的说明。只要是一个Object就可以加到ArrayList中去。
ArrayList看做一个动态数组,定义的时候不用指明其大小,里面只能存放对象,不能存
像int,float,double等primitive type
ArrayList<Double> a = new ArrayList<Double>();
public class TestCollection
{
public static void main(String [] args)
{
ArrayList a1=new ArrayList();
a1.add(new Integer(10));
a1.add(new Integer(2));
Iterator itr=a1.iterator();
int sum=0;
while(itr.hasNext())
{
Integer intObj=(Integer)itr.next();
sum=sum+intObj.intValue();
}
System.out.println(sum);
}
}