With the java.util.prefs.Preferences API is it possible to get historic results which are older than the last entry?
eg if you had
prefs.put("key", "value1");
prefs.put("key", "value2");
return prefs.get("key");
will return "value2" Can I ever get "value1" ?
If no then what is the best alternative to achieve this functionality.
If anyone can do better I am happy to accept their answer, in the mean time:
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;
public class RecentStrings
{
private final Preferences prefs;
private final int noRecent;
private static final int defaultNo = 10;
private final String indexingKey;
public RecentStrings()
{
this(Preferences.userRoot(), defaultNo, "r");
}
public RecentStrings(Preferences prefs, int noRecent, String indexingKey)
{
this.noRecent = noRecent;
this.prefs = prefs;
this.indexingKey = indexingKey;
}
public void setMostRecentString(String file)
{
if (!getAllRecentStrings().contains(file))
{
for (int i = noRecent-1; i >= 0; i--)
{
prefs.put(indexingKey+(i+1), prefs.get(indexingKey+i, ""));
}
prefs.put(indexingKey+0, file);
}
else
{
removeRecentString(file);
setMostRecentString(file);
}
}
private void removeRecentString(String file)
{
List<String> recents = getAllRecentStrings();
recents.remove(file);
for (int i=0; i < noRecent; i++)
{
String value;
if (i < recents.size())
{
value = recents.get(i);
}
else
{
value = "";
}
prefs.put(indexingKey+i,value);
}
}
public String getMostRecentString()
{
return prefs.get(indexingKey+0, "");
}
public List<String> getAllRecentStrings()
{
List<String> mostRecent = new ArrayList<>();
for (int i = 0; i < 10; i++)
{
String value = prefs.get(indexingKey+i, "");
if (!value.equals(""))
{
mostRecent.add(value);
}
}
return mostRecent;
}
}
Which also handles duplicates and keeps things from most recent to oldest.