java - 如何验证特定类型并创建我的列表 "type-safe"

标签 java

我正在尝试创建一个自定义列表,以确保只能在我的列表中添加一种类型的引用,我正在尝试使其“类型安全”。

数组已经设置为对象类型,并且所有内容都继承自对象,那么我如何替换/子类型?例如,如果我希望这个列表只能接受 String 对象。目前,我的程序可以采用 Integer 类型和 String 类型,如 main 方法中所示。

不幸的是,我不能为此使用泛型。

MyArrayList

import java.util.ArrayList;

public class MyArrayList implements MyList {

    private Object[] theList;
    private Object type;

    public MyArrayList() {
        theList = new Object[0];
    }

    public MyArrayList(Object type) {
        theList = new Object[0];
        setType(type);
    }

    public Object getType() {
        return type;
    }

    public void setType(Object type) {
        if (type == Integer.class || type == String.class || type == Double.class) {
            this.type = type;
        } else {
            System.out.println("Invalid value");
        }
    }

    public boolean add(Object toAdd) {

            if (toAdd != null && toAdd == type.getClass()) {
                Object[] temp = new Object[theList.length + 1];

                for (int index = 0; index < theList.length; index++) {
                    temp[index] = theList[index];
                }
                temp[theList.length] = toAdd;
                theList = temp;
                return true;
            } else {
                System.out.println("Invalid type");
                return false;
            }
        }

    public Object get(int index){

        if(index >= 0 && index < theList.length) {

            return theList[index];
        } else {
            return null;
        }
    }


    public Object remove(int index) {

        if (index >= 0 && index < theList.length) {
            Object[] newList = new Object[theList.length - 1];

            int j = 0;
            for (int i = 0; i < theList.length; i++) {
                if (i == index) {
                    continue;
                }
                newList[j++] = theList[i];
            }
            theList = newList;
            return newList;
        }
        return null;
    }


    public int size(){
        return theList.length;
    }

    public boolean isEmpty(){

        if(theList.length > 0) {
            return true;
        } else {
            return false;
        }
    }

    public void display() {
        for(Object thing: theList) {

            System.out.print(thing + ", ");
        }
        System.out.println();
    }

}

我的列表

/**
 * Write a description of interface List here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public interface MyList
{
    /**
     * Adds a new element at the end of the list.
     * @param the object to add
     * @return true if element successfully added, otherwise false
     */
    boolean add(Object toAdd);

    /**
     * Gets the object at the specified index.
     * @param index value of object to get
     * @return object at that index
     */
    Object get(int index);

    /**
     * Removes specified object from list.
     * @param index value of object to remove
     * @return the object removed
     */
    Object remove(int index);

    /**
     * Returns size of the list
     * @return number of elements in the list
     */
    int size();

    /**
     * @return true if the list has no elements, false otherwise
     */
    boolean isEmpty();

}

主要

import com.sun.jdi.IntegerType;

public class Main {

    public static void main(String[] args) {

        Object list = new Object();
        Object myList = new MyArrayList(list);
        MyArrayList newList = new MyArrayList(myList);


        newList.add(2);
        newList.add("Tom");
        newList.add(0.0);

        newList.display();


最佳答案

如果不使用泛型,就无法为此实现编译时类型安全。但是,如果您使用不是 java.lang.Object 的组件类型动态创建数组,并且

public class MyArrayList implements MyList {

    private Object[] theList;

    public MyArrayList(Class<?> type) {
        this.theList = (Object[]) java.lang.reflect.Array.newInstance(type, 10);
    }

    ...

这样,如果创建数组时传递的类是String.class,那么向其中添加一个整数将导致抛出java.lang.ArrayStoreException ,并且您可以在 this.theList[n] = object 所在的任何位置尝试/捕获此异常。

不过,值得一提的是,正确的方法是在您的类和调用者类中使用泛型。

关于java - 如何验证特定类型并创建我的列表 "type-safe",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64924872/

相关文章:

java - 创建 IndexSearcher 抛出 IOException 读取过去的 EOF

java - java中Instanceof的正确用法

java - 通过更改 URL 在 .Net Webservice 和 Java Webservice 之间切换

java - 如何在Hibernate中获取结果集

java - 链式 Observable

java - "Unexpected token: Void"for循环导致IDE处理错误,无论位置如何?

java - 具有自动重新连接功能的 JDBC 连接

java - 多对多关系 : org. hibernate.MappingException : Could not determine type for: java. util.Set

java - 如何在类中使用 List<String> 元素创建不可变类

java - 为什么aspectj 将测试文件夹中的方面编织到我的源类中(而不是测试类)?