java中怎么创建一个数组

Python010

java中怎么创建一个数组,第1张

Java 中创建数组的基本格式为 type[] varname = new type[size]{item1, item2, item3},其中 type 表示元素的类型, size 表示创建数组的大小,在指定后面所有元素的情况下,这个大小可以省略,后面花括号括起来的部分,用于指定元素,如果指定了大小,可以不要后面的部分,如以下语句军创建了一个数组;

int[] = new int[1]// 创建一个长度为1 的整形数组

int[] = new []{1}// 创建一个长度为1,第一个元素的值为1;

首先我们需要创建一个class:

class Student{  

    String name  

    double score  

    String num  

      

    Student(String n,double s,String m){  

        name=n  

        s=score  

        num=m  

    }  

  

    public static void printInfo(){  

        System.out.println(num+","+name+","+score)  

    }  

  

}

接下来我们对此类进行数组的创建:

//1  

Student stu[]<span style="white-space:pre">      </span>//声明数组。  

stu=new Student [3]<span style="white-space:pre">    </span>//创建数组,这里是创建的一个引用的数组,每一个引用并没有确切的地址。  

for(int i=0i<3i++){<span style="white-space:pre">    </span>//为数组创建对象,也就是说为创建的引用关联到确切的地址。  

    stu[i]=new Student()  

}  

//2  

Student stu[]=new Student [3]  

for(int i=0i<3i++){  

    stu[i]=new Student()  

}  

//3  

Student stu[]=new Student{new Student(sjl,87,01),new Student(ljs,98,02),new Student(lls,92,03)}

import java.util.ArrayList

import java.util.List

public class ClientSocket{

    public static void main(String[] args) throws Exception {

        List<Object> list = new ArrayList<Object>()//这里类型你自己指定

        list.add("asd")

        list.add(123)

        Object[] obj = new Object[list.size()]

        obj = list.toArray(obj)

    }

}

原理:ArrayList底层本身就是一个可变长度的数组,用ArrayList更方便,不用担心溢出。