Java程序用很多集合类,会不会很耗内存

Java程序用很多集合类,会不会很耗内存,第1张

对于一些集合类,为了维持其集合结构,会需要产生一些中间对象。不过这些中间对象的个数是跟你的集合中元素对象个数成正比。如果集合中元素的结构比较简单,个数较少,可能维持集合结构所创建的中间对象所耗内存比你的集合中元素所耗的内存还大;如果集合中元素的结构比较复杂,个数很大,相比之下,中间对象所耗内存基本可以忽略。这就得看你具体的应用考虑。

import javautilHashSet;

import javautilIterator;

public class Testcase {

int x1[], x2[];

Testcase(int a[], int b[]) {

x1=a;

x2=b;

}

Testcase(Testcase d) {

x1=dx1;

x2=dx2;

}

public void Jiaoji(Testcase a) {

for(int i=0; i < ax1length; i++){

for(int j=0; j < ax2length; j++){

if(ax1[i] == ax2[j])

Systemoutprint(ax1[i] + ",");

}

}

}

public static void main(String[] args) {

int x1[]= {

1, 4, 6, 9, 12, 18, 19, 45

};

int x2[]= {

4, 7, 9, 13, 19, 23, 29, 67

};

Testcase b=new Testcase(x1, x2);

bJiaoji(b);

Systemoutprintln("并集是;");

int union[]=union(x1, x2);

for(int i:union){

Systemoutprint(i+" ");

}

Systemoutprint("\n差集是: ");

int diff[]=difference(x1, x2);

for(int i:diff){

Systemoutprint(i+" ");

}

}

//并集

static public int[] union(int a[], int b[]) {

HashSet<Integer> set=new HashSet<Integer>();

for(int i:a){

setadd(new Integer(i));

}

for(int i:b){

setadd(new Integer(i));

}

int size=setsize();

int out[]=new int[size];

Iterator<Integer> iter=setiterator();

for(int i=0;i<size;i++){

//

//while(ihasNext()){

out[i]=((Integer)iternext())intValue();

}

return out;

}

//差集

static public int[] difference(int a[], int b[]) {

HashSet<Integer> set=new HashSet<Integer>();

for(int i:a){

setadd(new Integer(i));

}

for(int i:b){

setremove(new Integer(i));

}

int size=setsize();

int out[]=new int[size];

Iterator<Integer> iter=setiterator();

for(int i=0;i<size;i++){

out[i]=((Integer)iternext())intValue();

}

return out;

}

}

========

输出

4,9,19,并集是;

1 4 6 7 67 9 12 13 45 19 18 23 29

差集是: 1 18 6 12 45

==================

顺便练了下集合

以上就是关于Java程序用很多集合类,会不会很耗内存全部的内容,包括:Java程序用很多集合类,会不会很耗内存、用一个参数的JAVA程序实现集合的交并差运算、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zz/10071664.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-04
下一篇 2023-05-04

发表评论

登录后才能评论

评论列表(0条)

保存