英文:
Adding a object arraylist to a text
问题
我同时拥有字符串和整数数据类型,因此我创建了一个对象arrayList来容纳它们,但是当我想将对象arrayList添加到文本中时遇到了错误。这样做不可能吗?
以下是我的代码:
public class MainActivity extends AppCompatActivity {
public static List<Object> hi = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int converter = Integer.parseInt(editText.getText().toString());
converter = converter / 2;
if (copper1Pressed && copper2Pressed) {
convertedCost.setText("Converted cost: " + convert);
hi.add(editText.getText());
hi.add(converter);
editText.setText("");
String string1 = "Copper";
String string2 = "Copper";
for (Object edit : hi) {
edit = (string1 + " " + myList.get(0) + " = " + string2 + " " + myList.get(1));
txtList.setText(edit);
(注意:由于您要求仅返回翻译好的部分,我已经移除了您提供的代码中的代码部分,只保留了翻译后的内容。)
英文:
I have both string and integer data types so I have created an object arrayList to hold them both but have errors when I want to add the object arrayList to a text. Is this not possible to do?
Here is my code:
public class MainActivity extends AppCompatActivity {
public static List <Object> hi = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int converter = Integer.parseInt(editText.getText().toString());
converter = converter/2;
if (copper1Pressed && copper2Pressed) {
convertedCost.setText("Converted cost: " + convert);
hi.add(editText.getText());
hi.add(converter);
editText.setText("");
String string1 = "Copper";
String string2 = "Copper";
for(Object edit : hi){
edit = (string1 + " " + myList.get(0) + " = " + string2 + " " + myList.get(1));
txtList.setText(edit);
答案1
得分: 1
首先,不要这样做。这是一个糟糕的策略。
另一种解决方案可以是
- 如果您不需要知道实际类型,可以将int转换为String。
Object变量的问题在于容易犯错。
您的问题是int不是一个类。您不能将原生变量存储为对象,因为int并未扩展自Object类。然而,Integer将允许您正确执行应用程序。
英文:
First thing first, do not do that. It is bad strategy.
Alternative solution can be
- Converting int to String, if you do not need to know what is the actual type.
The problem with Object variable is, easy to make mistake.
Your problem is int is not a class. You cannot store a native variable as object, since int is not extended from Object class. Integer however will let you execute your application properly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论