简体   繁体   English

转换一个ArrayList <String> 到ArrayList <SomeClass> java的

[英]Convert an ArrayList<String> to ArrayList<SomeClass> java

I've managed to convert an arraylist of some class (in my case it's a class which extends ArrayAdapter<Question> ) to an ArrayList<String> . 我设法将某个类的arraylist(在我的情况下,它是扩展ArrayAdapter<Question> )转换为ArrayList<String> I've passed it through an android intent bundle and received through the getStringArrayList method. 我已经通过android意图包传递了它,并通过getStringArrayList方法接收了它。 Now I need to convert it back to the ArrayList<Question> to set my adapter up 现在我需要将其转换回ArrayList<Question>来设置我的适配器

Converting from ArrayList<Question> to ArrayList<String> ArrayList<Question>转换为ArrayList<String>

       questionlists = task.execute(myitem).get();

        for (Question object : questionlists) 
        {
            strings.add(object != null ? object.toString() : null);
        }
        simpleArray2 = new String[strings.size()];
        strings.toArray(simpleArray2);

Converting back to ArrayList<Question> 转换回ArrayList<Question>

 List<Question> variable;
 lists = getArguments().getStringArrayList("Question");
     variable = (List<Question>)(List<?>) lists;

  @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.main_world, container, false);
    ListView lv = (ListView) view.findViewById(R.id.list_sessions);
    final QuestionAdapter adapter = new QuestionAdapter(getActivity(), variable);
    lv.setAdapter(adapter);
    //ArrayAdapter<String> adapter = new ArrayAdapter<String>(  
             //inflater.getContext(), android.R.layout.simple_list_item_1,  
             //lists);  
   // lv.setAdapter(adapter);             
    return view;
}

I've added a try/catch my adapter and I get the error: 我添加了try / catch我的适配器,但出现错误:

java.lang.String cannot be cast to java.com.example.Question. 无法将java.lang.String强制转换为java.com.example.Question。

What am I doing wrong? 我究竟做错了什么? Is it because I haven't converted back to a proper ArrayList first? 是因为我没有先转换回适当的ArrayList吗?

In your first example, you're not actually casting a Question to a String . 在第一个示例中,您实际上并没有将Question强制转换为String You're calling the toString() method for a Question . 你调用toString()的方法Question

For example, 例如,

public class Question {

    //instance member
    String question;

    public String toString() {
       return question;
    }
}

In order to go from a String to a Question , you're going to have to write a constructor or method that takes a String as a parameter and returns a Question . 为了从StringQuestion ,您将必须编写一个以String为参数并返回一个Question的构造器或方法。

For example, you could add this constructor to your Question class: 例如,您可以将此构造函数添加到Question类中:

public Question(string myQuestion) {
     question = myQuestion;
}

Alright. 好的。 To convert from List<Question> to List<String> you already do this: 要将List<Question>转换为List<String>您已经执行了以下操作:

Converting from ArrayList to ArrayList 从ArrayList转换为ArrayList

   List<Question> questionlists = task.execute(myitem).get();
   List<String> strings = new ArrayList<String>();

    for (Question object : questionlists) 
    {
        strings.add(object != null ? object.toString() : null);
    }

Now to convert from List<String> to List<Question> you'd have to do exactly the same, just the other way round: 现在要从List<String>转换为List<Question>您必须完全相同,反之亦然:

   List<String> strings = ... result from above
   List<Question> questionlists = new ArrayList<Question>();

    for (String object : strings) 
    {
        questionlists.add(object != null ? object.toQuestion() : null);
    }

Oh, wait! 等一下! String does not have a toQuestion() method! String没有toQuestion()方法! What now? 现在怎么办? Well, we just make such a method ourselves. 好吧,我们自己做这种方法。 As it's going to be a method that creates a Question object, why not make it a Constructor of Question, taking a String as parameter? 由于它将成为创建Question对象的方法,为什么不以String为参数将其构造为Question的构造方法呢?

   List<String> strings = ... result from above
   List<Question> questionlists = new ArrayList<Question>();

   for (String object : strings) 
   {
       questionlists.add(object != null ? new Question(object) : null);
   } 

Now all that's left to do, is to add that Constructor to your question class. 现在剩下要做的就是将构造函数添加到您的问题类中。

class Question {
    public Question(String string) {
        // implementing this the right way is up to you...
    }
}

toString() is a method that all Java Object objects have. toString()是所有Java Object对象都具有的方法。 By default, it will list the name of the class and the memory location of the reference. 默认情况下,它将列出类的名称和引用的存储位置。 You're not actually converting the object Question to String . 您实际上并没有将对象Question转换为String You are generating a String that in some what interprets what Question is. 您正在生成一个在某种意义上解释什么是QuestionString For example, you can overwrite toString() to generate whatever you want. 例如,您可以覆盖toString()以生成所需的任何内容。

public class Question {

  String mQuestion;

  @Override
  public String toString() {
     return mQuestion;
  }
}

Now, what you can do is make some sort of custom String in toString() that fully represents your Question object. 现在,您可以做的是在toString()中创建某种自定义String,以完全表示您的Question对象。 Then have a fromString method that parses your custom String and builds new Question objects from it. 然后有一个fromString方法,用于解析您的自定义String并从中构建新的Question对象。 However, this method is error prone and limiting. 但是,此方法容易出错且有局限性。

A better method would be to either inherit Question from Serializable or better yet Parcelable . 更好的方法是从Serializable继承Question ,或者继承更好的Parcelable Doing this allows you to put the actual Question object in to a Bundle and pull it out from the Intent without any conversion. 这样做可以将实际的Question对象放入Bundle并将其从Intent中拉出,而无需进行任何转换。

You have to understand Type Casting correctly. 您必须正确理解类型转换。

Type casting is not conversion. 类型转换不是转换。 It is asking java to assume for the rest of that context that the real type of that object is what you say it is. 它要求Java在该上下文的其余部分假设该对象的真实类型就是您所说的。 You are telling java that even though it is not obvious in the current context, you know better about what the actual type of the object is. 您正在告诉Java,即使在当前上下文中它并不明显,您也可以更好地了解对象的实际类型。

Information about the exact type of an object is not available in every context. 并非在每个上下文中都提供有关对象的确切类型的信息。 As you pass objects around, methods treat them as any of their super class types right up to Object. 当您传递对象时,方法会将它们视为它们的任何超类类型,直到Object。

Type casting is a way to tell java that "I already know it is a List<Question> because I know who put that object there". 类型转换是一种告诉Java“我已经知道它是一个List <Question>,因为我知道是谁将该对象放在这里”的一种方式。

So, typecasting cannot help with conversion. 因此,类型转换无法帮助转换。 The object should already be of that type for typecasting to work. 该对象应该已经是该类型的类型转换才能起作用。

If it is of a different type, you have to write code to convert it. 如果类型不同,则必须编写代码将其转换。

public class ListProcessing {
public static void main(String[] args) {

    List<Integer> ints = Arrays.asList(1,2,3);

    //Take a list, convert and add to new list
    List<String> intStrs = listTransform(ints, new Converter<Integer, String>() {
        @Override
        public String convert(Integer input) {
            return input==null?null:"S"+input.toString();
        }           
    });

    System.out.println(intStrs);
}

//Generic list processor
protected static <T,U> List<U> listTransform(List<T> in, Converter<T,U> converter){
    if(in==null) return null;
    List<U> out = new ArrayList<>();
    for(T item:in){
        out.add(converter.convert(item));
    }
    return out;
}

//An interface for a converter, which converts a single item
private static abstract class  Converter <T,U>{
    public abstract U convert(T input);
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM