有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何获取通用列表intance的特定项

我不知道如何为泛型列表实例获取特定项。假设我有这样的东西

public class Column {

private String name;
private float width;

public Column(String name, float width) {
  this.name=name;
  this.width=width;
}
public String getName() {
    return name;
}

和另一类

public class WriteColumn {

private List<Column> col = new ArrayList<>();

public void addColumn() {
    col.add(new Column("yo", 0.1f));
    col.add(new Column("mo", 0.3f));
    writeColumn(col);

public void writeColumn(List<Column> col) {
    String str = "";
    for (Column col1 : col) {
        str += col1 + " - ";
    }
    System.out.println("Cols: " + str);
}


public static void main(String[] args) {
    WriteColumn wc = new WriteColumn();
    wc.addColumn();
}
}

我想要得到的输出是列的文本部分,但我没有得到它。有简单的方法吗


共 (2) 个答案

  1. # 1 楼答案

    下面的代码正在工作,输出: 科尔斯:哟-莫-

    我猜这就是你所期待的

    package com.vipin.test;
    
    import java.util.*;
    
    class Column {
    
        private String name;
        private float width;
    
        public Column(String name, float width) {
            this.name=name;
            this.width=width;
        }
        public String getName() {
            return name;
        }
    }
    
    public class WriteColumn {
    
        private List<Column> col = new ArrayList<>();
    
        public void addColumn() {
            col.add(new Column("yo", 0.1f));
            col.add(new Column("mo", 0.3f));
            writeColumn(col);
        }
        public void writeColumn(List<Column> col) {
            String str = "";
            for (Column col1 : col) {
                str += col1.getName() + " - "; //used getName()
            }
            System.out.println("Cols: " + str);
        }
    
    
        public static void main(String[] args) {
            WriteColumn wc = new WriteColumn();
            wc.addColumn();
        }
    }
    
  2. # 2 楼答案

    我不明白为什么不能使用getName()方法

    它应该起作用:

    public void writeColumn(List<Column> col) {
      String str = "";
      for (Column col1 : col) {
        str += col1.getName() + " - "; 
      }
      System.out.println("Cols: " + str);
    }