欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

Java中ArrayList和LinkedList以及queue的模仿,

来源: javaer 分享于  点击 26735 次 点评:161

Java中ArrayList和LinkedList以及queue的模仿,


    学习Java,对这种新的机制来说真的是很迷糊,一时间很多东西搞不明白怎么回事,Java的List接口有两种实现类分别是:ArrayList和LinkedList,二者利用的分别是数组和链表的实现原理,在一些不同场合的应用问题上会存在一定的性能的差异,上一篇博客中使用了一段简单的程序做了一个清晰的演示,这里主要是想试验一下利用list模拟queue的行为,看代码:

package play;

import java.util.LinkedList; 
import java.util.ArrayList;
import java.util.Random;
import java.util.NoSuchElementException; 
 
public class LinkedListTest { 
  private LinkedList<Integer> queue = new LinkedList<Integer>(); 
 
  public boolean isEmpty() { 
    return this.queue.isEmpty(); 
  } 
 
  public void enterQueue(int data) { 
    this.queue.addLast(data); 
  } 
 
  public int delQueue() throws NoSuchElementException { 
    return this.queue.removeFirst(); 
  } 
 
  public static void main(String[] args) { 
	  LinkedListTest q = new LinkedListTest(); 
	  //LinkedListTest qq = new LinkedListTest();
	  //qq.delQueue();//运行会报错NoSuchElementException
	  for (int i=0; i<100; i++){
		  Random ran = new Random();
		  int random = ran.nextInt(1000);//产生1000以内的100个随机数
		  q.enterQueue(random); 
	  }
 
    while (! q.isEmpty()) { 
      int data = q.delQueue(); 
      System.out.println(data); 
    } 
    System.out.println("--------------------------------------------------------------");
    LinkedList link_list = new LinkedList();
    String [] input = {"We","are","family!!!"};
    for(String one_word : input){
    	link_list.addFirst(one_word);
    }
    System.out.println("link_list:" + link_list);
	  System.out.println("--------------------------------------------------------------");
	  ArrayList array_list = new ArrayList();
	  String [] input2 = {"We","are","family!!!"};
	  for(String one_word : input2){
		  array_list.add(one_word);
	  }
	  System.out.println("array_list:" + array_list);
	  }
  } 

结果如下:

85
614
506
849
790
638
873
72
773
725
15
753
653
852
168
576
752
361
280
4
789
281
414
834
730
13
932
637
131
782
543
379
150
499
317
951
499
458
681
248
173
470
517
206
370
969
424
700
832
706
118
430
956
864
951
261
145
594
443
974
861
491
290
106
242
521
910
5
458
942
421
734
219
487
913
849
624
7
747
315
633
924
216
295
978
532
325
189
841
505
519
269
390
65
519
121
553
485
210
145
--------------------------------------------------------------
link_list:[family!!!, are, We]
--------------------------------------------------------------
array_list:[We, are, family!!!]


相关文章

    暂无相关文章

用户点评