将对象传递到Dlist

时间:2014-02-20 07:45:39

标签: java

/* DListNode1.java */

public class DListNode1 {


  public Object item;
//  public short[][] colorVal;
  public DListNode1 prev;
  public DListNode1 next;


  DListNode1() {
    item = 0;
    prev = null;
    next = null;
  }

  DListNode1(Object i) {
    item = i;
    prev = null;
    next = null;
  }
}
  /* Double linked list */
public class DList1 {

  protected DListNode1 head;
  protected DListNode1 tail;
  protected long size;

  public DList1() {
    head = null;
    tail = null;
    size = 0;
  }



  public DList1(Object a) {
    head = new DListNode1();
    tail = head;
    head.item = a;
    size = 1;
  }  
  public DList1(Object a, Object b) {
    head = new DListNode1();
    head.item = a;
    tail = new DListNode1();
    tail.item = b;
    head.next = tail;
    tail.prev = head;
    size = 2;
  }

  public void insertFront(Object i) {
    DListNode1 temp = new DListNode1(i);
    if (size == 0) {
      head = temp;
      tail = temp;
    }
    else {
      temp.next = head;
      head.prev = temp;
      head = temp;
    } size++;  
  }


  public void removeFront() {
    if (size == 0) {
      return;
    }
    else if (size == 1) {
      head = null;
      tail = null;
      size--;
    }
    else {
      head = head.next;
      head.prev = null;
      size--;
    }
  }

  public String toString() {
    String result = "[  ";
    DListNode1 current = head;
    while (current != null) {
      result = result + current.item + "  ";
      current = current.next;
    }
    return result + "]";
  }
public class num{
    public int j; 
    public num() {
      this.j = 34;
    }
   }
public class testing{
     private DList1 dli;
     private num n;

     public testing(){
     dli = new DList1();
     n = new num();
     dli.insertFront(n);} 
       public static void main(String[] args) {
           testing Jimmy = new testing();
           System.out.printf(" this should be 34 %d\n",Jimmy.dli.head.item.j);// dont' work.
       }
     }

有谁能告诉我为什么我不能做Jimmy.dli.head.item.j?它完全有道理,然而,它说“j无法解决或不是一个领域”。如何解决它以便打印34?没有这一行“dli.insertFront(n.j);”

1 个答案:

答案 0 :(得分:0)

  

项目是对吗?不是n.j = 34

是的,您已创建num对象并将其分配给item。但是,item仅是对Object num部分的引用 - 因此,通过此引用,您只能访问属于Object超类的成员( num隐式继承自Object)。

  

有没有办法访问34?

是的,您可以强制 Jimmy.dli.head.item返回num访问j成员,例如((num)Jimmy.dli.head.item).j

但是,实现此目的的正确方法是使DListNode1DList1 通用,而不是使用Object作为项元素:

public class DListNode1 <T> {
  public T item;
  ...

public class DList1 <T> {
  protected DListNode1<T> head;
  protected DListNode1<T> tail;
  ...

无论您在ObjectDListNode1课程中使用DList1,请立即使用T

然后,您可以实例化类似

的类型<{1}}
DList1

由于DList1<num> dli = new DList1<>(); 现在属于item类型而非num,因此您可以像预期的那样访问其Object元素:

j

另见The Java Tutorials, Lesson: Generics

顺便说一下,你应该习惯Code Conventions for the Java Programming Language - 例如类名应以大写字母开头(System.out.printf(" this should be 34 %d\n",Jimmy.dli.head.item.j); 而不是Testingtesting而不是Num。)