Problem faced with my history() method, how do I sort according to oldest change?

I am supposed to create a Trace class that encapsulates a variable of type T and its history of changes (as a List). A Trace object can be created using the static of method, passing in its value as the first argument and its (optional) history as the rest of the arguments. The history is always listed with the oldest change first.

This is what I have implemented:

import java.util.*;

@SuppressWarnings("unchecked")

class Trace<T>{
    ArrayList<T> objects;
    //int maxObjects;

    public Trace(T... words){
        this.objects = new ArrayList<T>();
        for (int i = 0; i < words.length; i++){
            objects.add(words[i]);
        }
    }

    public static <T> Trace<T> of(T... words){
        return new Trace(words);
    }

    public T get(){
        return this.objects.get(0);
    }

    public List<T> history(){
        return  this.objects;
    }

    public String toString(){
        String s = "[";
        for (int i = 0; i < this.objects.size() - 1; i++){
            String line = this.objects.get(i) + ", ";
            s += line;
        }
        s += this.objects.get(objects.size()-1) + "]";
        return s;
    }
}

However, when I ran my programme on Jshell, I am expected to get

jshell> Trace.of("hello").get()
$.. ==> "hello"
jshell> Trace.of("hello", "h", "he", "hel", "hell").get()
$.. ==> "hello"
jshell> Trace.of("hello", "h", "he", "hel", "hell").history()
$.. ==> [h, he, hel, hell, hello]

but instead, I am getting:

jshell> Trace.of("hello").get()
$.. ==> "hello"
jshell> Trace.of("hello", "h", "he", "hel", "hell").get()
$.. ==> "hello"
jshell> Trace.of("hello", "h", "he", "hel", "hell").history()
$.. ==> [hello, h, he, hel, hell]

How should I change my history() method such that it takes into account "hello" that was previously added, and returns "hello" in the list first, followed by h, he, hel, hell?

1 answer

  • answered 2019-10-08 03:37 aThorp96

    It seems like you need to separate the history from the word itself, or you need to make the history method a little smarter. Something like this would work if the first item in the input, the word, should always be the last item in the history.

        public List<T> history(){
            ArrayList<T> history = this.objects.sublist(1, this.objects.length());
            return history.add(this.get())
        }