在尝试实现自定义数据类时,我遇到了以下问题。我只是想向 ArrayList 添加项目,但 Java 似乎对我正在使用的类型有问题。我尝试了多种解决方案均无济于事。下面我包含了来自我的自定义数据类型的代码以及来自我的代码的简化版本,它们会引发相同的错误。我已经包含了我尝试过的两个解决方案以及每个抛出的错误/警告。
我对代码比较陌生,尤其是在 StackOverflow 上提出问题,所以如果我忘记了什么或者可以澄清,请告诉我。
自定义数据类型:
1 /**
2 This file defines a transition function data type
3 */
4
5 import java.util.ArrayList;
6
7 public class transition<X,Y,Z> {
8 private ArrayList<Integer> current;
9 private char scan;
10 private ArrayList<Integer> future;
11
12 //constructors
13 public transition(int x, char y, int z) {
14 this.current = new ArrayList<Integer>();
15 this.current.add(x);
16 this.scan = y;
17 this.future = new ArrayList<Integer>();
18 this.future.add(z);
19 }
20
21 public transition(ArrayList<Integer> x, char y, ArrayList<Integer> z) {
22 this.current = new ArrayList<Integer>();
23 this.current = x;
24 this.scan = y;
25 this.future = new ArrayList<Integer>();
26 this.future = z;
27 }
28
29 //methods
30 public ArrayList<Integer> getCurrent() {
31 return this.current;
32 }
33
34 public char getScan() {
35 return this.scan;
36 }
37
38 public ArrayList<Integer> getFuture() {
39 return this.future;
40 }
41 }
简化代码:
1 /**
2 Class designed to test out a bug encountered in my code
3 */
4
5 import java.util.ArrayList;
6
7 public class test {
8
9 public static void main(String[] args) {
10
11 //creating ArrayList and adding one transition to it
12 ArrayList<transition> list = new ArrayList<transition>();
13 transition trans = new transition(1, 'a', 2);
14 list.add(trans);
15
16 //creating list to add to
17 ArrayList<Integer> ints = new ArrayList<Integer>();
18
19 //testing loops over ArrayList and calls to trans
20 for(transition t : list) {
21
22 if(t.getCurrent().contains(1) && t.getScan() == 'a') {
23
24 //Option 1
25 ints.addAll(t.getFuture()); //t.java:24 warning: [unchecked] unchecked conversion
26 //found : java.util.ArrayList
27 //required : java.util.Collection<? extends java.lang.Integer>
28
29 //Option 2
30 for(Integer j : t.getFuture()) { // t.java:26: incompatible types
31 ints.add(j); // found : java.lang.Object
32 } // required : java.lang.Integer
33 }
34 }
35 }
36 }