Java: List常用方法入门

前言——容器的学习,刚开始建议先掌握一些基本概念。个人经验觉得,初学时,必须先从模仿开始,掌握基本方法,然后在平常的使用当中进一步深究,只会使用,内部原理一窍不懂也是不行的,debug的时候会无从下手,这篇文章纯粹的属于应用篇,入门使用篇,非常适合刚学习容器。对了,文章的精华是每个方法的例子,简单易懂真的推荐鸭

 

目录

Hero类作为测试类

一.使用数组的局限性

二.因为数组的局限性,引入了容器

三.容器的常用方法

四.ArrayList与List的关系


Hero类作为测试类

package Charactor;

import java.io.Serializable;
public  class Hero {

	public String name ;
	public float hp;
	public float damage;
	
	public Hero() {
		
		
	}
	public  Hero(String n, float h, float d) {
		name = n;
		hp = h;
		damage = d;
	}



	public float getHp() {
		
		return hp;
	}
    
    //重写Object方法是因为:
    //输出容器中的对象时,调用的是toString()方法,重写后可以输出自定义内容。
    public String toString(){

      return name;
    }
}

一.使用数组的局限性

数组虽然常用,但是数组的局限性很多,最明显的就是使用数组之前必须事先定义好长度。定义得过大,没用完会浪费空间,定义得过小,会不够用,无法自动扩大长度。

package Test;

import Charactor.Hero;

public class TestArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Hero [] heros = new Hero[10];//创建一个存放英雄对象的数组,长度为10
		
		for(int i = 0 ;i < 10 ;i++) { //存放10个英雄
			
			heros[i] = new Hero();
			
		}
		
		//打算存放第11个英雄,会报错
		heros[10] = new Hero();
		
		
		

	}

}

运行时会抛出下标越界的异常:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at Test.TestArray.main(TestArray.java:19)

 

二.因为数组的局限性,引入了容器

数组无法实现长度的动态增长,是引入容器的重要原因。这边先介绍一个容器,也算是用得比较多的——ArrayList。

容器提供了很多强大的功能,这边我给大家介绍容器最大的好处——容量可以动态增长。

package Test;

import java.util.ArrayList;

import Charactor.Hero;

public class TestArrayList {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		//创建一个ArrayList的容器对象,大家会发现不用指定长度
		ArrayList heros = new ArrayList();
		
		heros.add(new Hero());
		
		/*可以往容器里面加入无限个对象,优点很明显
		 heros.add(new Hero());
		 .....
		 .....
		 
		 
		 */
		//heros.size()用来返回容器的长度,也就是对象的个数
		System.out.println(heros.size());
		

	}

}

三.List的常用方法

1.增加一个对象——add

a  add(Object)

b. add(int i,Object)插入在第i个位置(i从0开始)

package Test;

import java.util.*;

import Charactor.Hero;

public class TestContainerMethod {
	
	  ArrayList heros = new ArrayList();
	  public static void main(String []args) {
	   
	    TestContainerMethod myTest = new TestContainerMethod();
	    myTest.addTest();
	  
	  
      }
   
   public void addTest() {
	   
	  	for(int i = 0 ;i < 5;i++) {
	  		
		    //方法1,直接把对象add在容器最后面
	  		heros.add(new Hero("hero" + i, 1,1));
	  		
	  	}
	  	//输出容器里面的内容
	  	System.out.println(heros);
	  	
	  	//方法2,把对象add在某个下标(下标从0开始)
		heros.add(2,new Hero("myHero" ,1 ,1));
		
		//再次输出容器里面的内容
		System.out.println(heros);
   }
}

2.判断某个对象是否在容器中------contains

contains(Object);

package Test;

import java.util.*;

import Charactor.Hero;

public class TestContainerMethod {
	
	  ArrayList heros = new ArrayList();
	  public static void main(String []args) {
	   
	    TestContainerMethod myTest = new TestContainerMethod();
	    myTest.containsTest();
	  
	  
      }
	   public void containsTest() {
		   
		  	for(int i = 0 ;i < 5;i++) {
		  		heros.add(new Hero("hero" + i, 1,1));
		  		
		  	}
		  	
		  	Hero myHero = new Hero();
		  	heros.add(2,myHero);
		  	
		  	//虽然这个对象的名字也是hero1,但是没有找到
		  	System.out.println(heros.contains(new Hero("hero1",2,2)) );
		  	
		  	//查询容器中是否存在和myHero指向共同对象的引用,输出的是True
		  	System.out.println(heros.contains(myHero));
	   }
}

/*
运行结果:
false
true
*/

 

这边要注意:容器中存储的都是引用,都是指向对象的引用。判断某个对象是否在容器中,其实就是判断容器中是否存在某个引用和传入的引用指向共同对象。不是查找名字相同的对象是否存在,这点要切记!!!

额外话题:那么如何找到name为"hero1"的元素呢?

思路:肯定是遍历啦,直接for循环+get()方法(下面就会介绍了,这边先贴个代码)

package Test;

import java.util.*;

import Charactor.Hero;

public class TestContainerMethod {
	
	  ArrayList heros = new ArrayList();
	  public static void main(String []args) {
	   
	    TestContainerMethod myTest = new TestContainerMethod();

	    myTest.isName();
	  
	      
      }
	  
	  public void isName() {
		  
		  for(int i =  0 ;i < 5 ;i++) {
			  
			  heros.add(new Hero("hero" + i ,1,1));
		  }
		  
		  /*  
          转化为数组来遍历也可以,不过麻烦了,多此一举
		  Hero [] myHero= (Hero [])heros.toArray(new Hero[]{});
		  
		  for(int i = 0 ;i < myHero.length ;i++) {
			  
			  if(myHero[i].name.equals("hero1")) {
				  
				  System.out.println("找到了");
				  break;
			  }
		  }
		  
		  System.out.println(heros);
		  */
		  

		  for(int i =  0 ;i < heros.size();i++) {
			  
			  Hero temp = (Hero )heros.get(i);
			  
			  if(temp.name.equals("hero1")) {
				  System.out.println("找到了");
				  break;
			  }
			  
		  }
		  
		  
	  }
}

 

 

3.获取指定位置的对象-----get

get(int index),   注意index不能越界,不然会抛出异常

package Test;

import java.util.*;

import Charactor.Hero;

public class TestContainerMethod {
	
	  ArrayList heros = new ArrayList();
	  public static void main(String []args) {
	   
	    TestContainerMethod myTest = new TestContainerMethod();
	    myTest.getTest();
	  
	  
      }
	  
   public void getTest() {
	   
	  	for(int i = 0 ;i < 5;i++) {
	  		heros.add(new Hero("hero" + i, 1,1));
	  		
	  	}
	  	
	  	Hero myHero = new Hero("myHero", 1,1);
	  	heros.add(2,myHero);
	  	
	  	//下标2,没有越界
	  	System.out.println(heros.get(2));
	  	
	  	//下标8,越界了,会报错
//	  	System.out.println(heros.get(8));
	   
   }
}
/*
运行结果:
myHero
*/

 

4.获取对象所处的位置-----indexOf

heros.indexOf(Object);

package Test;

import java.util.*;

import Charactor.Hero;

public class TestContainerMethod {
	
	  ArrayList heros = new ArrayList();
	  public static void main(String []args) {
	   
	    TestContainerMethod myTest = new TestContainerMethod();
	    myTest.indexOfTest();
	  
	  
      }
   public void indexOfTest() {
	   
	  	for(int i = 0 ;i < 5;i++) {
	  		heros.add(new Hero("hero" + i, 1,1));
	  		
	  	}
	  	
	  	Hero myHero = new Hero("myHero", 1,1);
	  	heros.add(2,myHero);
	  	
	  	//查找myHero这个对象,能查找到,输出2
	  	System.out.println(heros.indexOf(myHero));
	  	
	  	//查找新创建的对象,没能查找到,输出-1
	  	System.out.println(heros.indexOf(new Hero("hero1",1,1)));
   }
}
  /*
运行结果:
2
-1
*/

这和contains一样,判断的是容器中是否有某个引用和要查询的引用指向同一对象,弄不懂的同学,要去学习一下引用的概念。

 

5.删除容器中的对象

可以通过下标来删除------remove(int index)

也可以通过对象来删除------remove(Object);

package Test;

import java.util.*;

import Charactor.Hero;

public class TestContainerMethod {
	
	  ArrayList heros = new ArrayList();
	  public static void main(String []args) {
	   
	    TestContainerMethod myTest = new TestContainerMethod();
	    myTest.removeTest();
	  
	  
      }
   public void removeTest() {
	   
	  	for(int i = 0 ;i < 5;i++) {
	  		heros.add(new Hero("hero" + i, 1,1));
	  		
	  	}
	  	
	  	Hero myHero = new Hero("myHero", 1,1);
	  	heros.add(2,myHero);
	  	
	  	System.out.println(heros);
	  	
	  	//移除容器中下标1对应的对象
	  	heros.remove(1);
	  	System.out.println(heros);
	  	
	  	//移除容器中的myHero对象
	  	heros.remove(myHero);
	  	System.out.println(heros);
	  	
	  	
	  	
   }
}
/*
运行结果:
[hero0, hero1, myHero, hero2, hero3, hero4]
[hero0, myHero, hero2, hero3, hero4]
[hero0, hero2, hero3, hero4]
*/

 

6.替换容器中某个位置的元素

set(int index ,Object)

package Test;

import java.util.*;

import Charactor.Hero;

public class TestContainerMethod {
	
	  ArrayList heros = new ArrayList();
	  public static void main(String []args) {
	   
	    TestContainerMethod myTest = new TestContainerMethod();
	    myTest.setTest();
	  
	  
      }
	  
   public void setTest() {
	   
	  	for(int i = 0 ;i < 5;i++) {
	  		heros.add(new Hero("hero" + i, 1,1));
	  		
	  	}
	  	
	  	Hero myHero = new Hero("myHero", 1,1);
	  	heros.add(2,myHero);
	  	
	  	System.out.println(heros);
	  	
	  	System.out.println("把下标是3的元素替换成\" myHero2\" ");
	  	heros.set(3, new Hero("myHero2",1,1));
	  	
	  	System.out.println(heros);
	  	
   }
}

/*
运行结果:
[hero0, hero1, myHero, hero2, hero3, hero4]
把下标是3的元素替换成" myHero2" 
[hero0, hero1, myHero, myHero2, hero3, hero4]
*/

 

7.获取容器当前的长度,也就是当前存储的对象的数量

size();

package Test;

import java.util.*;

import Charactor.Hero;

public class TestContainerMethod {
	
	  ArrayList heros = new ArrayList();
	  public static void main(String []args) {
	   
	    TestContainerMethod myTest = new TestContainerMethod();
	    myTest.sizeTest();
	  
	  
      }
   public void sizeTest() {
	   
	  	for(int i = 0 ;i < 5;i++) {
	  		heros.add(new Hero("hero" + i, 1,1));
	  		
	  	}
	  	
	  	Hero myHero = new Hero("myHero", 1,1);
	  	heros.add(2,myHero);
	  	
	  	System.out.println("当前长度为:" + heros.size());
	   
   }
}

 

8.转化为某种类型的数组

toArray();

有两种重载方法:

toArray():返回的是Object类型的数组,无参,不允许强制装换, 比如(T [])toArray()是错误的

toArray(T[] t): 返回的是Object类型的数组,有参数,需要传一个数组对象,一般用这个方法

package Test;

import java.util.*;

import Charactor.Hero;

public class TestContainerMethod {
	
	  ArrayList heros = new ArrayList();
	  public static void main(String []args) {
	   
	    TestContainerMethod myTest = new TestContainerMethod();
	    myTest.toArrayTest();
	  
	  
      }
	  
	  
	public void toArrayTest() {
		   
	  	for(int i = 0 ;i < 5;i++) {
	  		heros.add(new Hero("hero" + i, 1,1));
	  		
	  	}
	  	
	  	Hero myHero = new Hero("myHero", 1,1);
	  	heros.add(2,myHero);
	  	
	  	//这边要注意,应该传一个Hero类型的数组对象给toArray()
	  	Hero [] temp = (Hero [])heros.toArray(new Hero [] {});
	  	
	  	System.out.println(temp);
   }
		   
}

/*
运行结果:
[LCharactor.Hero;@7852e922
*/

9.把另一个容器的所有对象加进来

addAll(Colection c);

package Test;

import java.util.*;

import Charactor.Hero;

public class TestContainerMethod {
	
	  ArrayList heros = new ArrayList();
	  public static void main(String []args) {
	   
	    TestContainerMethod myTest = new TestContainerMethod();
	    myTest.addAllTest();
	  
	  
      }
	  
	public void addAllTest() {
		
	  	for(int i = 0 ;i < 5;i++) {
	  		heros.add(new Hero("hero" + i, 1,1));
	  		
	  	}
	  	ArrayList myHeros = new ArrayList();
	  	
	  	myHeros.add(new Hero("hero5",2,2));
	  	myHeros.add(new Hero("hero6",2,2));
	  	
	  	heros.addAll(myHeros);
	  	
	  	System.out.println(heros);
	  	
	  	
		
	}
}

/*
运行结果:
[hero0, hero1, hero2, hero3, hero4, hero5, hero6]
*/

10.清空一个容器

clear();

package Test;

import java.util.*;

import Charactor.Hero;

public class TestContainerMethod {
	
	  ArrayList heros = new ArrayList();
	  public static void main(String []args) {
	   
	    TestContainerMethod myTest = new TestContainerMethod();
	    myTest.clearTest();
	  
	  
      }
	  
	 public void clearTest() {
		 
			
		  	for(int i = 0 ;i < 5;i++) {
		  		heros.add(new Hero("hero" + i, 1,1));
		  		
		  	}
		  	
		  	heros.clear();
		  	System.out.println(heros);
	 }
}
/*
运行结果:
[]
*/

四.ArrayList与List的关系

ArrayList实现了List接口:

public class ArrayList<E> extends AbstractList<E>
   implements List<E>, RandomAccess,Cloneable,java.io.Serializable{
}

上面所介绍的10种方法都是实现List中的方法得到的,我们有时也可以创建一个List的引用,令这个引用指向ArrayList的对象(多态)

package Test;

import java.util.*;

import Charactor.Hero;

public class TestContainerMethod {
	

	  public static void main(String []args) {
	   

	    List myheros = new ArrayList();
	    
	    myheros.add(new Hero("myHero",1,1));
	    
	    System.out.println(myheros);

	  
	      
      }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值