Java class: for getOrder, getData, updateData operation

Posted on

Problem

Problem Statement :

Design a class for three operations for given set of integers :

int getOrder(int data) /* order meaning rank in list */
int getData(int order)
void updateData(int oldData, int newData) /* [Most used operation] */

My solution

class App {

    Set<Integer> appData; 

    public App(List<Integer> data) {
        this.appData = new TreeSet<Integer>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                if(o1 > o2) {
                    return -1;
                } else if (o1 < o2) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        appData.addAll(data);
    }


    public int getOrder(int m) {
        int counter = 1;
        for(Integer i : this.appData) {
            if(i == m) {
                return counter;
            }
            counter ++ ;
        }
        return -1;
    }

    public int getdata(int order) {
        int counter = 1;
        for(Integer data : this.appData) {
            if(counter == order) {
                return data;
            }
            counter++;
        }
        return -1;
    }

    public void updatedata(int olddata, int newdata) {
        if(appData.contains(olddata)) {
            this.appData.remove(olddata);
        }
        this.appData.add(newdata);
    }
}

Solution

(Please post working code next time.)

So first off, there are imports missing, so this doesn’t compile as it
is, and the variable mark doesn’t exist.

import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.Comparator;

Either you import by name, or the whole package, just stick with one.

...
        if(counter == order) {
            return data;
        }
...

Then you should generally specify the visibility on all things,
otherwise you end up with package visibility, which is probably not what
you want.

public class App {
...
private Set<Integer> appData;

Use of generics is good, the constructor is okay except for the
unnecessary manual comparison. This should be either using
TreeSet.descendingSet, or Comparator.reverseOrder, e.g.:

public App(List<Integer> data) {
    this.appData = new TreeSet<Integer>(Comparator.<Integer>reverseOrder());
    appData.addAll(data);
}

Some whitespace is also off and the spelling of methods should be
consistent, i.e. getdata should be get getData and updatedata
should be updateData as is mentioned in your spec.

That just to get you started here.

Leave a Reply

Your email address will not be published. Required fields are marked *