1

Can the contains() method from the Vector class in Java be manipulated from another class (without expanding the Vector class)?

Let's say we have this:

class AuxType {
    String name;
    int type;

    AuxType(String name, int type) {
        this.name = name;
        this.type = type;
    }
}

class Main {
    void aMethod() {
        Vector<AuxType> v = new Vector<AuxType>();
        v.add(new AuxType("a", 1));
        v.add(new AuxType("b", 2));
        v.add(new AuxType("c", 3));

        for (int i = 0; i < v.size(); i++) {
            if (v.get(i).type == 2) {
                System.out.println("Found it!");
            }
        }
    }
}

The for/if lines could be written as

if (v.contains(2)) {
    //
}

Is a way through which I can change how contains() works (either in the AuxType class or in the aMethod() function from Main)?

EDIT: NOT A DUPLICATE

I wasn't asking about calling a method from a class, but about changing it without extending that class.

tasegula
  • 889
  • 1
  • 12
  • 26
  • You're asking if you can use a method from another class without (a) extending that class, (b) composing an instance of that class, or (c) using some sort of heinous bytecode manipulation? No. – Dave Newton Dec 30 '13 at 18:47
  • I wasn't asking about calling a method from a class, but about changing it without extending that class. – tasegula Dec 30 '13 at 18:51

1 Answers1

2

What you are looking for is called mixin, and no, it's not available in Java.

In Java this problem is solved by using inheritance (and it does make perfectly sense although is somewhat verbose).

Theoretically it is possible to add a method dynamically without directly defining a new class but it's really complicated and overdone for the task.

Just extend the class or define an utility method.

Community
  • 1
  • 1
Jack
  • 131,802
  • 30
  • 241
  • 343