package cn.com.wangxiukai;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Test {
public static void main(String[] args) {
Entity tac=new Entity(1, "东川地震了", "大家");
Entity tar=new Entity(2, "黄河水满了", "我");
LinkedList hehe =new LinkedList();
hehe.addFirst(tac);
hehe.addLast(tar);
Entity tttt=(Entity) hehe.getFirst();
Entity tt=(Entity) hehe.getLast();
hehe.remove();
for (int i = 0; i <hehe.size(); i++) {
Entity uu=new hehe.get(i);
//为什么会出错呀?
System.out.println((i+1)+uu.getName());
}
}
}
实体类:
private String id;
private String name;
private int num;
public User(int num,String id, String name) {
this.id = id;
this.name = name;
this.num = num;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
测试:
User u=new User(1, "东川地震了", "大家");
User u1=new User(2, "黄河水满了", "我");
//用泛型让其记住存取类型 就如数组中User[] u=new User[5];
User[] use=new User[5];
use[0]=u;
use[1]=u1;
LinkedList<User> llu=new LinkedList<User>();
llu.addFirst(u);
llu.addLast(u1);
User ur=llu.getFirst();
User us=llu.getLast();
User ur1=use[0];
User ur2=use[1];
for(int i=0;i<llu.size();i++){
// User为定义类型 ue为变量名 llu.get(i)拿出来的是对象 如果没有用泛型那就需要强转下
User ue=llu.get(i);
System.out.println((i+1)+"\t"+ue.getName());
}
[code="java"]Entity uu=new hehe.get(i); [/code]
你这个是什么写法?
应该是
[code="java"] for (int i = 0; i <hehe.size(); i++) {
Entity uu = hehe.get(i); [/code]
你的写法有误,你的写法语法有问题,编译都通过不了
问题出在:
for (int i = 0; i <hehe.size(); i++) {
Entity uu=[color=red]new[/color] hehe.get(i);
应该为:Entity uu= hehe.get(i);即可.
这句:
Entity uu=new hehe.get(i);
1.new 关键字,是用来创建新对象用的,也就是说你需要一个对象为你服务,那么可以通过这个关键字进行创建,比如你的: Entity tac=new Entity(...)
2.等号,这里表示赋值,属于地址赋值。
比如你可以先写:Entity tac1 = null.表示空的,然后 tac1 = tac;表示tac 的地址值赋给tac1了,他们相当于共用一个对象了。
3.hehe.get(i); 表示你从集合里面取出位置在 i 的的对象,
而 Entity uu = hehe.get(i);这样表示你将取出的对象,赋值给变量uu.
4.关于对象 赋值 集合这些 基础,你可以去看看JAVA SE 的书籍。JAVA 变成思想上面的前几章都有介绍