List接口的實(shí)現(xiàn)類
- ArrayList實(shí)現(xiàn)了長(zhǎng)度可變的數(shù)組朗涩,在內(nèi)存中分配連續(xù)的空間忽孽。遍歷元素和隨機(jī)訪問(wèn)元素的效率比較高
-
LinkedList采用鏈表存儲(chǔ)方式。插入谢床、刪除元素時(shí)效率比較高
手動(dòng)輸入狗狗
package com.company;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
/**
* Created by ttc on 2018/1/8.
*/
public class ListDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// String[] arrays = new String[100000000];
List<String> listDogs = new ArrayList<>();//創(chuàng)建List集合對(duì)象
while (true)
{
System.out.println("請(qǐng)輸入一條狗的名字兄一,no退出");
String dogName = scanner.next();
listDogs.add(dogName);//向List中添加元素
if(dogName.equals("no"))
{
break;
}
}
//遍歷數(shù)組
//listDogs.size()獲得集合當(dāng)前元素的個(gè)數(shù)
for(int i = 0; i < listDogs.size(); i++)
{
System.out.println(listDogs.get(i));//listDogs.get(i)獲得集合中第i個(gè)元素的值
}
System.out.println("退出了");
}
}
手動(dòng)輸入刪除喵星人
Scanner scanner=new Scanner(System.in);
List<String> listCats=new ArrayList<String>();
while (true)
{
System.out.println("請(qǐng)輸入一個(gè)喵星人的名字");
String catName=scanner.next();
if (catName.equals("no"))
{
break;
}
if (!listCats.contains(catName))
{
listCats.add(catName);
}
}
System.out.println("需要?jiǎng)h除第幾條喵星人");
int delete=scanner.nextInt();
listCats.remove(delete);
System.out.println("需要?jiǎng)h除哪只喵星人");
String delete1=scanner.next();
listCats.remove(delete1);
for (int i=0;i<listCats.size();i++)
{
System.out.println(listCats.get(i));
}
System.out.println("退出");
調(diào)用類的方法
Scanner scanner=new Scanner(System.in);
List<Cat> catList=new ArrayList<Cat>();
while (true)
{
System.out.println("請(qǐng)輸入喵星人的名字");
String catName=scanner.next();
if (catList.equals("no"))
{
break;
}
Cat cat=new Cat();
cat.setName(catName);
catList.add(cat);
for (int i=0;i<catList.size();i++)
{
Cat cat1=catList.get(i);
System.out.println(cat1.getName());
}
System.out.println("退出");
}
類的編寫(xiě)
```java
package com.company;
/**
* Created by ttc on 18-1-8.
*/
public class Cat {
private String name;
private int age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
}