2016-05-31 84 views
1

我想程序从方法readA()readB()打印的回报,但我从main指出valueB需要String,String,因为我的构造GenericMemoryCell()的得到一个错误。但是,如果我需要通过构造函数接收和存储2个参数,我不需要发送2个参数给构造函数,如下所示?我怎么能只分配一个字符串到valueBGenericMemoryCell类GenericMemoryCell <T>不能应用于给定类型

public class GenericMemoryCell<T>{ 

    public static void main(String[] args) { 
     GenericMemoryCell<String> valueA = new GenericMemoryCell<String>("1", "1"); 
     GenericMemoryCell<String> valueB = new GenericMemoryCell<String>("1"); 
     System.out.println("storedValueA: " + valueA.readA()); 
     System.out.println("storedValueB: " + valueB.readB()); 
    } 

    public GenericMemoryCell(T storedValueA, T storedValueB) 
    { this.storedValueA = storedValueA; this.storedValueB = storedValueB; writeA(storedValueA); writeB(storedValueB); } 

    public T readA() 
    { return storedValueA; } 

    public T readB() 
    { return storedValueB; } 

    private T storedValueA, storedValueB; 
} 

回答

0

如果你想创建GenericMemoryCell路过你需要添加第二个构造带一个参数一个参数。

这里是一个PARAM构造函数只是调用两个PARAM构造函数,传递一个空的第二值的例子:

public GenericMemoryCell(T storedValueA, T storedValueB) { 
    ... 
} 

public GenericMemoryCell(T storedValueA) { 
    this(storedValueA, null); 
} 
0

这里是如何去创建一个只分配1字符串VALUEB更多构造函数与单个参数:

public GenericMemoryCell(T storedValueB) { 
    this.storedValueB = storedValueB;  
} 

因此,现在您的类看起来如下所示。我编辑了几个地方来改进它。就像你的构造函数中有两个参数一样,不需要调用:writeA(storedValueA)writeB(storedValueB)

GenericMemoryCell.java

public class GenericMemoryCell<T> { 

    public static void main(String[] args) { 
     GenericMemoryCell<String> valueA = new GenericMemoryCell<String>("1", "2"); 
     GenericMemoryCell<String> valueB = new GenericMemoryCell<String>("3"); 
     System.out.println("valueA (A): " + valueA.readA()); 
     System.out.println("valueA (B): " + valueA.readB()); 
     System.out.println("valueB (A): " + valueB.readA()); 
     System.out.println("valueB (B): " + valueB.readB()); 
    } 

    public GenericMemoryCell(T storedValueA, T storedValueB) { 
     this.storedValueA = storedValueA; 
     this.storedValueB = storedValueB; 
    } 

    public GenericMemoryCell(T storedValueB) { 
     this.storedValueB = storedValueB; 
    } 

    public void writeB(T storedValueB) { 
     this.storedValueB = storedValueB; 

    } 

    public void writeA(T storedValueA) { 
     this.storedValueA = storedValueA; 

    } 

    public T readA() { 
     return storedValueA; 
    } 

    public T readB() { 
     return storedValueB; 
    } 

    private T storedValueA, storedValueB; 
} 
相关问题