當前位置:首頁 » 編程語言 » java遍歷刪除

java遍歷刪除

發布時間: 2023-02-10 04:38:45

1. java List遍歷方法及其效率對比

Java代碼

package zbalpha test;

import java util ArrayList;

import java util Iterator;

import java util List;

public class ListTest {

public static void main(String args[]){

List<Long> lists = new ArrayList<Long>();

for(Long i= l;i< l;i++){

lists add(i);

}

Long oneOk = oneMethod(lists);

Long oOk = oMethod(lists);

Long threeOk = threeMethod(lists);

Long fourOk = fourMethod(lists);

System out println( One: + oneOk);

System out println( Two: + oOk);

System out println( Three: + threeOk);

System out println( four: + fourOk);

}

public static Long oneMethod(List<Long> lists){

Long timeStart = System currentTimeMillis();

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

System out println(lists get(i));

}

Long timeStop = System currentTimeMillis();

return timeStop timeStart ;

}

public static Long oMethod(List<Long> lists){

Long timeStart = System currentTimeMillis();

for(Long string : lists) {

System out println(string);

}

Long timeStop = System currentTimeMillis();

return timeStop timeStart ;

}

public static Long threeMethod(List<Long> lists){

Long timeStart = System currentTimeMillis();

Iterator<Long> it = erator();

while (it hasNext())

{

System out println(it next());

}

Long timeStop = System currentTimeMillis();

return timeStop timeStart ;

}

public static Long fourMethod(List<Long> lists){

Long timeStart = System currentTimeMillis();

for(Iterator<Long> i = erator(); i hasNext();) {

System out println(i next());

}

Long timeStop = System currentTimeMillis();

return timeStop timeStart ;

}

}

容器類可以大大提高編程效率和編程能力 在Java 中 所有的容器都由SUN公司的Joshua Bloch進行了重新設計 豐富了容器類庫的功能

Java 容器類類庫的用途是 保存對象 它分為兩類

Collection 一組獨立的元素 通常這些元素都服從某種規則 List必須保持元素特定的順序 而Set不能有重復元素

Map 一組成對的 鍵值對 對象 即其元素是成對的對象 最典型的應用就是數據字典 並且還有其它廣泛的應用 另外 Map可以返回其所有鍵組成的Set和其所有值組成的Collection 或其鍵值對組成的Set 並且還可以像數組一樣擴展多維Map 只要讓Map中鍵值對的每個 值 是一個Map即可

迭代器

迭代器是一種設計模式 它是一個對象 它可以遍歷並選擇序列中的對象 而開發人員不需要了解該序列的底層結構 迭代器通常被稱為 輕量級 對象 因為創建它的代價小

Java中的Iterator功能比較簡單 並且只能單向移動

( ) 使用方法iterator()要求容器返回一個Iterator 第一次調用Iterator的next()方法時 它返回序列的第一個元素

( ) 使用next()獲得序列中的下一個元素

( ) 使用hasNext()檢查序列中是否還有元素

( ) 使用remove()將迭代器新返回的元素刪除

Iterator是Java迭代器最簡單的實現 為List設計的ListIterator具有更多的功能 它可以從兩個方向遍歷List 也可以從List中插入和刪除元素

List的功能方法

List(interface): 次序是List最重要的特點 它確保維護元素特定的順序 List為Collection添加了許多方法 使得能夠向List中間插入與移除元素(只推薦 LinkedList使用) 一個List可以生成ListIterator 使用它可以從兩個方向遍歷List 也可以從List中間插入和刪除元素

ArrayList: 由數組實現的List 它允許對元素進行快速隨機訪問 但是向List中間插入與移除元素的速度很慢 ListIterator只應該用來由後向前遍歷ArrayList 而不是用來插入和刪除元素 因為這比LinkedList開銷要大很多

LinkedList: 對順序訪問進行了優化 向List中間插入與刪除得開銷不大 隨機訪問則相對較慢(可用ArrayList代替) 它具有方法addFirst() addLast() getFirst() getLast() removeFirst() removeLast() 這些方法(沒有在任何介面或基類中定義過)使得LinkedList可以當作堆棧 隊列和雙向隊列使用

Set的功能方法

Set(interface): 存入Set的每個元素必須是唯一的 因為Set不保存重復元素 加入Set的Object必須定義equals()方法以確保對象的唯一性 Set與Collection有完全一樣的介面 Set介面不保證維護元素的次序

HashSet: 為快速查找而設計的Set 存入HashSet的對象必須定義hashCode()

TreeSet: 保持次序的Set 底層為樹結構 使用它可以從Set中提取有序的序列

LinkedHashSet: 具有HashSet的查詢速度 且內部使用鏈表維護元素的順序(插入的次序) 於是在使用迭代器遍歷Set時 結果會按元素插入的次序顯示

lishixin/Article/program/Java/hx/201311/26494

2. java遍歷list 並刪除相同值對象

用一個for循環遍歷List時,不能刪除其中的元素。

用Iterator操作即可。

還有 Pro類要重寫一下 toString方法。這樣System.out.println里才能列印出來。

import java.util.*;

public class ListTest {
public static void main(String[] args) {

List<Pro> list = new ArrayList();
Pro p1 = new Pro("1000","1000");
Pro p2 = new Pro("1001","1002");
Pro p3 = new Pro("1003","1004");
Pro p4 = new Pro("1005","1006");
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);

for (Iterator<Pro> i = list.iterator(); i.hasNext();) {
Pro o = i.next();
if(o.getProid().equals(o.getProName())){
i.remove();
}
}
System.out.println(list);
}
}

class Pro{
private String proid;
private String proName;

public String getProid() {
return proid;
}
public void setProid(String proid) {
this.proid = proid;
}
public String getProName() {
return proName;
}
public void setProName(String proName) {
this.proName = proName;
}
public Pro(String proid, String proName) {
super();
this.proid = proid;
this.proName = proName;
}
public Pro() {
}

public String toString() {
return proid + ":" + proName;
}
}

3. Java中遍歷ArrayList的過程中刪除元素操作會發生並發修改異常

首先搞清楚不是x=n-1不報錯。是因為他避開了錯誤,實際當你用倒數第2個來刪除的時候,他就已經跳出循環,不會判斷最後以為,這是為什麼呢?

我們先看看加強for循環是怎麼實現的。都知道是通過迭代實現,那麼將for寫成迭代器來看。

Iterator<Object>itr=al.iterator();
while(itr.hasNext()){
Objecto=itr.next();
System.out.println(itr.hasNext());
if("n".equals(o)){
al.remove(o);
}
}

以上就是加強for循環的真正樣子。再來透析源代碼。

al.iterator():返回一個迭代器沒什麼好說的;

itr.hasNext():通過判斷cursor(游標) != size(長度)來決定是否結束循環,cursor(游標) 初始是0 每次經過itr.next() +1;當cursor==size時 會跳出循環,這也是為什麼倒數第2個不會出錯的主要原因;

itr.next(): 看源代碼可以發現每次在next()調用後,都會先調用checkForComodification()這個方法;

checkForComodification(): 主要作用是判斷itr迭代器數據是否和list一致,

有兩個參數,

第一個modCount 集合結構變動次數,如:一開始你add調用了7次,那麼這個數就是7,

第二個expectedModCount 在調用iterator()方法時,初始化值等於modCount ,

這個方法判斷當modCount !=expectedModCount 時

拋出異常,如果你調用迭代器的remove方法,expectedModCount 會重新賦值,但是你調用的是list的remove方法,那麼modCount 就會+1 而expectedModCount 不變,這就會造成modCount !=expectedModCount;

最後,看看為什麼倒數第2個不會拋異常:

當他遍歷到「n-1」時,cursor=6,然後調用remover(o)方法,size=6,這個時候調用了itr.hasNext()判斷cursor是否等於size,前面說過,當cursor==size時,跳出循環,那麼就不會進入next(),也就不會進入checkForComodification()方法,所以不會拋出異常,說白了,也就是循環次數少了一次。

結合著源碼看,應該會比較清晰。

4. JAVA中HashMap如何刪除元素

HashMap刪除元素根據其遍歷方式一般有兩種方法,實例演示如下:

一、採用foreach模式,適用於不需要修改HashMap內元素的遍歷,只需要獲取元素的鍵/值的情況。

1、遍歷如下:

原因在於,迭代器遍歷時,每一次調用 next() 函數,至多隻能對容器修改一次。上面的代碼則進行了兩次修改:一次添加,一次刪除。

5. java 多線程操作hashtable(添加,刪除,遍歷)

public class TestThread {
public static void main(String[] args){
Map<Integer, Object> tables = new Hashtable<Integer, Object>();
Thread add = new Thread(new ThreadAdd(tables));
Thread del = new Thread(new ThreadDel(tables));
Thread count = new Thread(new ThreadCount(tables));
//啟動線程
add.start();
del.start();
count.start();
}
/**
*添加對象線程
*/
private static class ThreadAdd implements Runnable{
private Map<Integer, Object> table;

public ThreadAdd(Map<Integer, Object> tables){
this.table=tables;
}
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
table.put(i, new Object());
System.out.println("添加對象,序號為:"+i);
}
}
}
/**
*刪除對象線程
*/
private static class ThreadDel implements Runnable{
private Map<Integer, Object> table;

public ThreadDel(Map<Integer, Object> table){
this.table=table;
}
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
table.remove(i);
System.out.println("移除對象,序號為:"+i);
}
}
}
/**
*統計線程
*/
private static class ThreadCount implements Runnable{
private Map<Integer, Object> table;

public ThreadCount(Map<Integer, Object> table){
this.table=table;
}
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("當前隊列還剩"+table.size()+"個對象");
}
}
}
}
這是我的寫的demo,不知道符合不符合你的意思,大家共同交流共同進步。

6. java List 遍歷和刪除 急

List可以用序號來遍歷,但通常推薦使用iterator來遍歷
Iterator itr = list.iterator();
while (itr.hasNext()) {
Object nextObj = itr.next();
}

如果要全部刪除,用clear()方法是最簡單的。
另外,Iterator也帶有remove()方法,可以在遍歷的時候,根據一定條件來進行刪除。

示例:

import java.util.*;

public class Test {
public static void print(List<Integer> list) {
Iterator<Integer> itr = list.iterator();
while (itr.hasNext()) {
System.out.print(itr.next());
System.out.print(", ");
}
System.out.println();
}

public static void main(String[] args) {
List<Integer> s = new ArrayList<Integer>();
for (Integer i = 0; i < 10; i++) {
s.add(i);
}
print(s);

Iterator<Integer> itr = s.iterator();
while (itr.hasNext()) {
Integer i = itr.next();
if (i % 3 == 0) {
itr.remove();
}
}
print(s);
}
}

7. java中的集合哪些可以邊遍歷邊刪除,哪些不可以,還有哪些可以邊遍歷邊添加哪些不可以

都可以,關鍵是小心別越界了!

確切的說你應該注意遍歷的方式和增刪的方式是否一致(即:普通循環和迭代器別混合用)。

或者你的意思是有哪些集合是線程安全的,可兩個線程一個遍歷一個操作。這個api里有。
凡是自身是線程安全的都可以,不是就要自己實現線程安全,但還是小心別越界。

8. java用迭代器邊遍歷邊刪除的問題

if ((Integer.parseInt((String) it.next()) == 9)
|| (Integer.parseInt((String) it.next()) == 12)) {

你這個判斷有問題,你執行了兩次 next()方法。

這樣改以下。

int i = Integer.parseInt((String) it.next();
if ((i == 9)|| (i == 12)) {

9. java:用Iterator遍歷對象中,刪除因元素不符合的對象,並顯示出來

Vector<Student> stu = new Vector<Student>(6);
stu.add(new Student(1001,"張三"));
stu.add(new Student(1002,"李四"));
stu.add(new Student(1003,"王五"));
stu.add(new Student(1004,"趙六"));
stu.add(new Student(1005,"趙小寶"));
stu.add(new Student(1006,"張小明"));
Iterator<Student> iter = stu.iterator();
while(iter.hasNext()){
String s =iter.next().getName();
if(s.length()==3){
System.out.println(s);
iter.remove();
}
}

熱點內容
java返回this 發布:2025-10-20 08:28:16 瀏覽:751
製作腳本網站 發布:2025-10-20 08:17:34 瀏覽:1012
python中的init方法 發布:2025-10-20 08:17:33 瀏覽:719
圖案密碼什麼意思 發布:2025-10-20 08:16:56 瀏覽:879
怎麼清理微信視頻緩存 發布:2025-10-20 08:12:37 瀏覽:774
c語言編譯器怎麼看執行過程 發布:2025-10-20 08:00:32 瀏覽:1127
郵箱如何填寫發信伺服器 發布:2025-10-20 07:45:27 瀏覽:351
shell腳本入門案例 發布:2025-10-20 07:44:45 瀏覽:229
怎麼上傳照片瀏覽上傳 發布:2025-10-20 07:44:03 瀏覽:912
python股票數據獲取 發布:2025-10-20 07:39:44 瀏覽:876