Hey Guys我对Java很新,我在使用泛型方面有点挣扎。 基本上我想迭代存储在Set-class中的转换集合。如果我创建一个Set类的实例我没有遇到任何问题,但我想迭代存储在FA类中的转换,这会导致一些麻烦(无法将Object转换为Transition)。必须有一些问题与代码,但我无法找到它:(
public static void main(String[] args) {
FA fa = new FA( new Set<String>("A", "B", "C"),
"A",
new Set<Transition>(new Transition("A", 1, "B"),
new Transition( "B",2,"C")),
new Set<String>("C") );
Set<Transition> t=new Set();
t.add(new Transition("A", 1, "B"));
for (Transition transition : t) {
//Works as intended
}
//error cannot convert Object to Transition
for (Transition transition : fa.Transitions) {
//not working
}
FA级:
public class FA<T>
{
public Set<T> States;
public T StartState;
public Set<Transition> Transitions;
public Set<T> FinalState;
public FA(){}
public FA( Set<T> states, T startstate, Set<Transition> transitions, Set<T> finalstate) {
States = states;
StartState = startstate;
Transitions= transitions;
FinalState = finalstate ;
}
}
设置级:
public class Set<T> implements Iterable<T>
{
private ArrayList<T> Menge=new ArrayList<T>();
public Set( T ... menge ) {
for( int i=0; i < menge.length; i++ ) {
Menge.add((T) menge[i] );
}
}
public int count() {
return Menge.size();
}
public T get(int i) {
return (T)Menge.get(i);
}
public void add(T i) {
Menge.add((T)i);
}
@Override
public String toString() {
return Menge.toString();
}
@Override
public Iterator<T> iterator() {
// TODO Auto-generated method stub
return Menge.iterator();
}
}
过渡级:
public class Transition<T>
{
private T Source;
private T Label;
private T Target;
public Transition( T source, T label, T target ) {
Source = source;
Label = label ;
Target = target;
}
public T get(int i)
{
if(i==1)return Source;
if(i==2)return Label;
return Source;
}
@Override
public String toString() {
return Source.toString() + " - " + Label.toString() + " -> " + Target.toString();
}
}
答案 0 :(得分:1)
fa的声明是错误的,它应该是:
FA<Transition> fa = new FA<>( new Set<String>("A", "B", "C"),
"A",
new Set<Transition>(new Transition("A", 1, "B"),
new Transition( "B",2,"C")),
new Set<String>("C") );
顺便说一下,在通用实例化中还有一些其他错误,我建议你阅读http://docs.oracle.com/javase/tutorial/java/generics/