[Java]我该如何完成这个分类程序。 [英] [Java]how can I complete this classification program.

查看:89
本文介绍了[Java]我该如何完成这个分类程序。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何完成此分类程序。我想将元素添加到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.
Hi

Just write the corrensponding overloaded add method, e.g.

public void add(Integer t)
{
  // add to 'integer' ArrayList
}


这篇关于[Java]我该如何完成这个分类程序。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆