首页 > 解决方案 > Java UML 图

问题描述

我需要一些帮助将此 UML 图转换为代码。对于我的任务,我们必须使用 arrayList,但我不确定如何在类中使用它。这是我必须翻译的 UML:

java.util.ArrayList<Integer> Set 
+Set (elements: int...) 
+Set (clone: Set) 
+intersection (intersectionSet: Set) 
+union (unionSet: Set) 
+difference (differenceSet: Set)

这是主要应该是什么:

public static void main(String[] args) {

         Set setA = new Set(1,2,3,4);
         System.out.println(setA);

         Set setB = new Set(2,5);
         System.out.println(setB);

         Set setC = new Set(setA);
         setC.intersection(setB);
         System.out.println("intersection:" + setC);

         setC = new Set(setA);
         setC.union(setB);
         System.out.println("union: "+ setC);

         setC = new Set(setA);
         setC.difference(setB); 

         System.out.println("difference:" + setC);

    }

这就是我到目前为止所拥有的。我觉得我的课程应该是他们应该的方式,但我不确定如何处理 ArrayLists。任何帮助都会很棒!

import java.util.ArrayList;

public class Set {

    ArrayList<Integer> setAList = new ArrayList<>();
    ArrayList<Integer> setBList = new ArrayList<>();
    ArrayList<Integer> setCList = new ArrayList<>();

    Set setA;
    int int1, int2, int3, int4;

    public Set() {
    }

    public Set(int int1, int int2, int int3, int int4) { //setA
        this.int1 = int1;
        this.int2 = int2;
        this.int3 = int3;
        this.int4 = int4;
    }

    public Set(int int1, int int2) { //setB
        this.int1 = int1;
        this.int2 = int2;
    }

    public Set(Set setA) {
        this.setA = setA;
    }

    public int getInt1() {
        return int1;
    }

    public void setInt1(int int1) {
        this.int1 = int1;
    }

    public int getInt2() {
        return int2;
    }

    public void setInt2(int int2) {
        this.int2 = int2;
    }

    public int getInt3() {
        return int3;
    }

    public void setInt3(int int3) {
        this.int3 = int3;
    }

    public int getInt4() {
        return int4;
    }

    public void setInt4(int int4) {
        this.int4 = int4;
    }

    public void intersection(Set setB) { }

    public void union(Set setB) { }

    public void difference(Set setB) { }

再次任何帮助将不胜感激!

标签: javaarraylist

解决方案


UML 缺少部分,但从您的代码中,我假设您正在寻找类似的内容:

public class Set { // Class name defined in top section
    ArrayList<Integer> set;   // Package attribute in middle section

    public Set(Integer...elements) {
        // populate set with elements
    }

    public Set(Set set) {
        // populate set with set.elements
    }

    public void intersection(Set set) {
        // remove from this.set where element not in set
    }

    // continue with other methods.
}

本质上,所有交互都应该this.set通过基于该方法更新值来进行。您不需要所有其他字段,因为它们不在 UML 图中。


推荐阅读