Question

I am sorry if this question is silly question, but I have hard time to understand the usage of Object []. I want to know what does below method really return. because it is enveloped as an object. Why i m asking this because i want to replace this method with other method to integrate with other module.

What I understand it would return list of Value Object? But what is this Object[] really means?

Thank you soo much.

public Object[] generateNewGreedySolution(int startingPoint) {
    if (startingPoint == -1) {
        startingPoint = new Random().nextInt(ins.getDimension() + 1);
    }

    //Solution s = new Solution(problem);
    Object[] values = new Object[ins.getDimension()];

    List<Integer> cities = new ArrayList<Integer>();
    for (int i = 0; i < ins.getDimension(); i++) {
        if ((i + 1) != startingPoint) {
            cities.add(i + 1);
        }
    }

    values[0] = startingPoint;
    for (int i = 1; i < values.length; i++) {
        double minCost = -1;
        int index = -1;

        for (int j = 0; j < cities.size(); j++) {
            double distance = ins.getDistance(startingPoint, cities.get(j));

            if (distance < minCost || minCost == -1) {
                minCost = distance;
                index = j;
            }
        }

        values[i] = cities.get(index);
        startingPoint = cities.get(index);

        cities.remove(index);
    }

    return values;
}
Was it helpful?

Solution 2

your generateNewGreedySolution method returns an array of Object Type

In the 5th line you are doing

Object[] values = new Object[ins.getDimension()];

So here values is an object array and hence you are returing the same.

If you are confused of what to return in methods then please note that if your method signaure is int then you should return int,if your method signature is String then you should return String.

Here your method return type is Object[] and so you are returning values

OTHER TIPS

Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.

from: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

Meaning that you are able to use an array of the type Object to return a collection of just about every class object. For example you could have the object with index 0 be an Integer another one being a String.

But since "only" all the classes are inherited, you need to notice that primitives are NOT. What I mean with that is that there is for example a difference between int (primitive) and an java.lang.Integer (which is inherited from said Object and has an int member variable, but can also point to null).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top