首页 > 解决方案 > Java Vector:每个元素包含三个对象。如何根据其中之一的价值进行操作?

问题描述

例如,我有vector(object1, object2, price). 如何打印价格 > 100 的元素?

所有教程和文档(关于以这种方式操作)我只看到处理向量,其中每个元素只包含一个对象。

那么我怎样才能获得元素内一个特定对象的句柄呢?或者这甚至可能吗?

一个附带问题:那些叫什么?也就是说,如果一个元素由多个项目组成,那么这些项目叫什么?与数据库一样,记录由字段组成。很难用谷歌搜索你不知道名字的东西。

主要的:

import java.util.Vector;

public static void main(String[] args){
    Scanner sc=new Scanner(System.in);
    String type;
    String location;
    double value;

    System.out.print("type->");
    type=sc.nextLine();

    System.out.print("location->");
    location=sc.nextLine();

    Property prop=new Property(type,location);

    System.out.print("value->");
    value=sc.nextDouble();

    InsuranceInfo insu=new InsuranceInfo(prop,value);
    container.addInsuranceInfo(insu);
}

InsInfoContainer 类:

public class InsInfoContainer {
    private Vector<InsuranceInfo> container;

    public InsInfoContainer() {
        container = new Vector<>(3, 1);
    }

    public void addInsuranceInfo(InsuranceInfo insu) {
        container.addElement(insu);
    }

public void print() {
        Iterator<InsuranceInfo> iter = container.iterator();
        while (iter.hasNext()) {System.out.println(iter.next());}
    }

保险信息类:

public class InsuranceInfo {
    public InsuranceInfo(Property prop, double value) {
        this.prop = prop;
        this.value = value;
    }

    private Property prop;
    private double value;

    public Property getProp() {return prop;}
    public void setProp(Property prop) {this.prop = prop;}
    public double getValue() {return value;}
    public void setValue(double value) {this.value= value;}
}

属性类:

public class Property {

    private String type;
    private String location;

    public Property(final String type, final String location) {
        this.type = type;
        this.location = location;
    }

    public String getType() {return this.type;}
    public void setType(final String type) {this.type = type;}
    public String getLocation() {return this.location;}
    public void setLocation(final String sijainti) {this.location = location;}
}

标签: javavectorelement

解决方案


你有一个容器来存储你的InsuranceInfo

private Vector<InsuranceInfo> container;

  1. containerCollection
  2. InsuranceInfo里面的实例container被称为element
  3. InsuranceInfo您在( Property, ) 内的“项目”value被称为propertyfieldelement

要遍历您的container集合,通常的方法是使用for循环或foreach循环:

public void print() {
    for (InsuranceInfo element: container) {
       if (element.getValue() > 100) { // Here is your condition to filter elements
          // Process your elements here
       }
    }
}

您也可以使用Iterator,Stream来做到这一点。


推荐阅读