「java动态数组的创建」java动态数组创建语句

博主:adminadmin 2023-01-23 06:15:08 319

今天给各位分享java动态数组的创建的知识,其中也会对java动态数组创建语句进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

如何用java语言创建不定长动态数组

public class intArray {

private int theSize=0;;

private int a_int[]={};

public intArray(int a[]){

this.a_int=a;

this.theSize=a.length;

}

public intArray(){

this.theSize=0;

}

public int getSize(){

return this.theSize;

}

public int getAt(int nIndex){

return this.a_int[nIndex];

}

public void SetAt(int nIndex , int newElement){

this.a_int[nIndex] =newElement;

}

public void add(int nIndex){

int old[] = this.a_int;

this.a_int= new int[this.theSize+1];

for(int i =0;iold.length;i++){

a_int[i]= old[i];

}

if(this.theSize0){

a_int[this.theSize]=nIndex;

}else{

a_int[0]=nIndex;

}

this.theSize++;

}

public static void main(String args[]){

intArray array = new intArray();

array.add(1);

array.add(2);

array.add(3);

array.add(4);

array.add(5);

for(int i = 0;iarray.getSize();i++){

System.out.println(array.getAt(i));

}

}

}

再给个任意类型的

public class myArray AnyType{

private int theSize=0;

private AnyType theItem[]=null;

public myArray(AnyType a[]){

this.theItem=a;

this.theSize=a.length;

}

public myArray(){

}

public int getSize(){

return this.theSize;

}

public AnyType get(int nIndex){

return this.theItem[nIndex];

}

public void Set(int nIndex , AnyType newElement){

this.theItem[nIndex] =newElement;

}

public void add(AnyType newVal){

AnyType old[]=this.theItem;

this.theItem= (AnyType[]) new Object[theSize+1];

if(theSize!=0){

for(int i =0;iold.length;i++){

this.theItem[i]= old[i];

}

}

this.theItem[this.theSize]=newVal;

this.theSize++;

}

public static void main(String args[]){

myArrayString array = new myArrayString();

array.add("1");

array.add("2");

array.add("3");

array.add("a");

array.add("b");

array.add("c");

for(int i =0;iarray.theSize;i++){

System.out.println(array.get(i));

}

}

}

java如何定义动态数组

JAVA中的数组没有动态的

要是想用动态的数据结构就用向量Vector

采用Vector

import java.until.Vector;

例如:

Vector vet==new Vector();

String str="test1";

double t1=0.124;

vet.add(str);

vet.add(String.valueOf(t1));

可以用 vet.size()获取其大小。

通过vet.get(i);获取第i个元素(i从0开始),类型为Object,转换一下就可以了。

具体可以查看jdk api文档

java中如何创建动态数组

所谓的匿名数组,个人感觉都是被动创建的如:

public

class

main

{

实用例子:

public

static

void

main(string[]

args)

{

out1(new

string[]

{"1",

"2"});

//第一种匿名数组

out2("1",

"2");

//第二种

}

static

void

out1(string[]

ss){

for

(string

str

:

ss)

{

system.out.println(str);

}

}

static

void

out2(string...

ss){

for

(string

str

:

ss)

{

system.out.println(str);

}

}

}

JAVA中 静态,动态创建数组的区别,联系?

区别:

1,数组创建时间不同,静态的是一定义出来就创建了,动态的则是定义时不创建,使用时才创建,一定意义上节省了内存空间。

2,使用场景不同,一开始就知道数组长度的使用静态初始化,反之,动态初始化。

联系:

其实没有什么联系,最恰当的方法用在最适合的场景里就行了

关于java动态数组的创建和java动态数组创建语句的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。