[Java]我该如何完成这个分类程序。 [英] [Java]how can I complete this classification program.
问题描述
我如何完成此分类程序。我想将元素添加到corressponding数组列表。
公共类分类< T> {
private ArrayList< T> integer = new ArrayList< T>();
private ArrayList< T> Double = new ArrayList< T>();
private ArrayList< T> string = new ArrayList< T>();
private ArrayList< T> character = new ArrayList< T>();
public void add(T t){
if(t.toString()== t){
string.add(t);
} else {
integer.add(t);
}
}
}
我尝试了什么:
我尝试使用
if((double)t == t){
Double .add(t)
}
但是,它给出了一条错误消息,即operator ==无法应用于T
Quote:public class Classification< t> {
由于您的类应该对传递的数据进行分类,因此将其依赖于通用参数是没有意义的。
Quote:private ArrayList< t> integer = new ArrayList< t>();
private ArrayList< t> Double = new ArrayList< t>() ;
private ArrayList< t> string = new ArrayList< t>();
private ArrayList< t> character = new ArrayList< t>();
如果事先知道它们只包含一种类型,为什么要创建通用ArrayList。例如,你为什么不使用
private ArrayList< Integer> integer = new ArrayList< Integer>();?
Quote:我想将元素添加到corressponding数组列表。
您好只需写相应的响应重载
添加
方法,例如
public < span class =code-keyword> void add(整数t)
{
// 添加到'整数'ArrayList
}
How can I complete this classification program. I would like to add element to corressponding array list.
public class Classification<T> { private ArrayList<T>integer = new ArrayList<T>(); private ArrayList<T>Double = new ArrayList<T>(); private ArrayList<T>string = new ArrayList<T>(); private ArrayList<T>character = new ArrayList<T>(); public void add(T t){ if (t.toString()==t){ string.add(t); }else{ integer.add(t); } } }
What I have tried:
I try to use
if ((double)t == t){ Double.add(t) }
However, it gives me an error message which is operator == cannot be applied to T
Quote:public class Classification<t> {
Since your class should classify passed data, it makes no sense making it dependent upon a generic parameter.
Quote:private ArrayList<t>integer = new ArrayList<t>();
private ArrayList<t>Double = new ArrayList<t>();
private ArrayList<t>string = new ArrayList<t>();
private ArrayList<t>character = new ArrayList<t>();
Why are you creating generic ArrayList when you know in advance they will hold just one type. For instance, why don't you use
private ArrayList<Integer>integer = new ArrayList<Integer>();?
Quote:I would like to add element to corressponding array list.
HiJust write the corrensponding overloaded
add
method, e.g.
public void add(Integer t) { // add to 'integer' ArrayList }
这篇关于[Java]我该如何完成这个分类程序。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!