Java数组简介
数组是用来在一个名称下保存元素的集合。这里传递的是一个相同类型的元素集合。如果你有一个值的列表来存储它,如果没有数组,你必须声明元素,如果有200个值,你必须声明200个声明。
String str1="one"
String str3="two"
String str3="three"
数组不需要对多个值进行声明,而是在一个单一的变量名下存储元素的集合。数组中的每个元素都可以通过使用索引来访问。数组的索引总是从零开始,最大长度是长度-1。
数组的特点
使用length方法找出数组元素的长度,就像一个对象。
数组中的元素是有序的,可以使用索引进行检索
数组中的每个元素都实现了可克隆和可序列化的接口
它创建了动态内存
数组语法
数组声明语法如下
Datatype variableName[] or Datatype[] variableName;
阵列初始化语法
variableName=new Datatype[size]
在初始化过程中,需要在内存中创建一个大小的空间。
如何在java中创建和初始化数组?
数组可以通过多种方式创建。使用字面意义或使用新操作符。下面的例子是关于原始数组类型的创建。
int[] array1 = new int[]{8,7,2,4 };
int[] array2 = {8,7,2,4 };
int array3[] = new int[5]
String array creation and initialize
String[] stringArray = new String[10];
String[] stringArray1 = { "one", "two", "three", "four", "five" };
String[] stringArray2 = new String[] { "one", "two", "three", "four", "five" };
如何声明和初始化对象数组?
一个对象数组可以像原始类型一样被创建,五个雇员对象被创建并存储在数组中,并有雇员对象的引用。
Employe[] list=new Employee[5]
Employee{
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
单维和二维数组程序实例
单个数组就像普通的数组声明和初始化一样
Integer [] ints=new Integer[5]
多维数组包含数组的数组 申报一个多维数组
Integer twoDArrays[][]=new Integer[2][2];
twoDArrays[0][0]=1;
twoDArrays[0][1]=2;
twoDArrays[1][0]=2;
twoDArrays[1][1]=3;
如何从数组中创建和初始化ArrayList?
这是一个将数组数据复制到ArrayList的例子。Arrays.asList方法将数组作为输入并返回集合,ArrayList构造函数用集合进行初始化并返回ArrayList对象。
String[] strs = { "one", "two", "three", "four", "five" };
ArrayList listStrings = new ArrayList(Arrays.asList(strs));
System.out.println(listStrings); // outputs [one, two, three, four, five]
如何找出数组中是否存在元素/对象?
这是一个在元素或对象的数组中寻找元素的例子。首先,使用asList方法将数组转换为集合。集合有一个方法contains(),如果一个元素存在于集合中,则返回true,否则返回false。
String[] strs = { "one", "two", "three", "four", "five" };
System.out.println(Arrays.asList(strs).contains("ade")); // outputs false
System.out.println(Arrays.asList(strs).contains("one")); // outputs true
如何在java中把数组转换为集合,并举例说明?
有时需要将数组数据复制到集合。Set不允许有重复的元素。如果数组包含重复的元素,将数组复制到Set将不允许存储重复的元素。更多信息见下面的例子
String[] strs = { "one", "two", "three", "four", "five" ,"five"};
Set set=new HashSet(Arrays.asList(strs));
System.out.println(set); // outputs [four, one, two, three, five]
如何通过例子在java中反转一个数组的元素?
首先,使用asList方法将数组转换为集合。然后应用Collections.reverse方法来反转该集合
String[] strs = { "one", "two", "three", "four", "five" ,"five"};
List listStrs = Arrays.asList(strs);
System.out.println(listStrs); //outputs [one, two, three, four, five, five]
Collections.reverse(listStrs);
System.out.println(listStrs); // outputs [five, five, four, three, two, one]