[英]Generic return types in a singly linked list
我正在使用與通用對象的鏈接列表一起工作的程序,在定義單個列表的類內部,有一種方法可以返回該鏈接的值:
public class Link<E> {
private E _value;
public E getValue() {
return _value;
}
然后,我想在鏈接鏈接類中使用類型為<E>的返回值來返回列表中某個位置的鏈接值
public class LinkedList <E> implements List <E> {
public E get(int index){
Link current = goTo(index); //go to is a helper method that returns a pointer to a Link at position index
E value = current.getValue(); //this is the source of the problem
return value;
}
}
這個問題與通用類型<E>有關,我不完全了解它是如何工作的。
更新資料
我收到消息: Type mismatch: cannot convert from Object to E
在源中指示的行上Type mismatch: cannot convert from Object to E
看來您應該這樣做:
Link<E> current = goTo(index);
如Link current
(無<E>
)指向Object類的列表。
實現它時,必須為type參數提供實際類型。 下面給出一個示例。
package com.example.transformer;
/**
* This represents the transformer contract to transform domain objects into
* data transfer objects.
*
* @param <S>
* source to be transformed.
* @param <T>
* result after the transformation.
*/
public interface Transformer<S, T> {
T transform(S source);
}
這是實現,
package com.example.transformer;
import com.example.domain.dto.OrderDetailsDTO;
import com.example.domain.dto.ProductDetailsDTO;
import com.example.domain.dto.ShippingDetailsDTO;
public class ProductDetailsDTOTOOrderDetailsDTOTransformer implements Transformer<ProductDetailsDTO, OrderDetailsDTO> {
private ShippingDetailsDTO shippingInformation;
public ProductDetailsDTOTOOrderDetailsDTOTransformer(ShippingDetailsDTO shippingInformation) {
super();
this.shippingInformation = shippingInformation;
}
@Override
public OrderDetailsDTO transform(ProductDetailsDTO source) {
return new OrderDetailsDTO(source.getName(), source.getUnitPrice() + shippingInformation.getCost(),
source.getUnitPrice(), source.getCurrency(), source.getSoldBy(),
shippingInformation.getCourierService(), shippingInformation.getAddress(),
shippingInformation.getCost());
}
}
注意,在實際實現中, S
和T
被實際類型ProductDetailsDTO
和OrderDetailsDTO
替代。 在您的情況下,Iny可能會是這樣。
public class LinkedList <YourType> implements List <E> {
// your code goes here ...
}
希望這可以幫助。 快樂的編碼。
我認為您的問題是這一行:link current = goTo(index); 您必須更正它以指定要使用的對象的類型: Link <TypeOfObject> current = goTo(index);
用goTo方法的返回類型值替換“ TypeOfObject。我假設它是一個整數,所以如果是這種情況,只需將Link <TypeOfObject> current = goTo(index);
替換為Link <Integer> current = goTo(index);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.