Ordered Set based on linked list - java

I am working with java, and I need to implement an ordered set, base on a linked list using the interface SortedSet. How do I implement the methods from SortedSet by this conditions?

Since this is clearly homework (or a similar learning exercise) it is inappropriate to give you code. So here are some Hints to get you started.
You need to keep the elements of the linked list ordered at all times
If the linked list is a wrapped LinkedList, you can delegate a lot of the SortedSet methods to the list.
Alternatively, consider using AbstractSet as the base class for your set.
(You will need to check the wording of your homework's requirement to figure out if you are allowed to use LinkedList or AbstractList.)

As I understand, you need to use Set feature to delete duplicates from your LinkedList, and to use SortedSet to keep it sorted.
So, the easiest way to do that, if you have a linked list, is to do something like this. For this example I've used LinkedList which would be filled with random numbers:
public class Main {
public static void main(String[] args){
//Declare the LinkedList of Integers
LinkedList<Integer> linkedList = new LinkedList<Integer>();
//use special method to fill List with 10 numbers which are less than 100
linkedListRandomFill(linkedList, 10, 100);
//After you pass the LinkedList to the following constructor
// the list is sorted automatically
SortedSet<Integer> sortedSet = new TreeSet<Integer>(linkedList);
//After that you can recreate your linked list,
// just pass the SortedSet to LinkedList constructor
linkedList = new LinkedList<Integer>(sortedSet);
System.out.println(linkedList);
}
public static void linkedListRandomFill(
LinkedList<Integer> linkedList,
int size,
int limit){
Random rnd = new Random();
for(int i = 0; i < size; i++){
linkedList.add(rnd.nextInt(limit));
}
}
Also we could refactor that:
public class Main {
public static void main(String[] args){
LinkedList<Integer> linkedList = new LinkedList<Integer>();
linkedListRandomFill(linkedList, 10, 100);
linkedList = getSortedListOfUniqueValues(linkedList);
System.out.println(linkedList);
}
public static void linkedListRandomFill(
LinkedList<Integer> linkedList,
int size,
int limit){
Random rnd = new Random();
for(int i = 0; i < size; i++){
linkedList.add(rnd.nextInt(limit));
}
}
public static LinkedList<Integer> getSortedListOfUniqueValues(LinkedList<Integer> list){
SortedSet<Integer> sortedSet = new TreeSet<Integer>(list);
return new LinkedList<Integer>(sortedSet);
}
}

Related

To merge two sorted linked lists. Is there a better way to create new Linked list heads in java?

In this program, I have created the head node inside the class LinkedList.
public class LinkedList {
public class Node {
public int data;
public Node next;
}
Node Head=null
void IntersectionOfTwoSortedLists(Node ListA, Node ListB){
while (ListA!=null && ListB!=null) {
if (ListA.data == ListB.data){
System.out.println(ListA.data);
InsertAtEnd(ListA.data);
}
if(ListA.data<ListB.data)
ListA=ListA.next;
else
ListB=ListB.next;
}
}
and the main function in a different class looks like this.
public static void main(String[] args) {
LinkedList list = new LinkedList();
LinkedList list2= new LinkedList();
for(int i=0;i<n;i++){
list.InsertAtEnd(sc.nextInt());
}
System.out.println("Enter the list 2 elements");
for(int i=0;i<n;i++){
list2.InsertAtEnd(sc.nextInt());
}
LinkedList intersect= new LinkedList();
intersect.IntersectionOfTwoSortedLists(list.Head,list2.Head);
creating a new object of the linked list class every time a good practice or is there a better way to do this? Thanks in advance!
If you perform operations over two different lists in such case you have to create two different objects. you can use copy but here in your case, it will not work because if you do so then update in one list will affect others too.

Im having trouble understanding how to pass an array to a method, and return an array list

I am having trouble finishing this intro to Java assignment. My goal is pass nums[] into the method array() and then have array() return an ArrayList containing all of the "freezing" temps found in nums[]. Any help would be appreciated
import java.util.ArrayList;
import java.util.Arrays;
public class Program73 {
public static int[] array(int[] array) {
return array;
}
public static void main(String[] args) {
int nums[] = new int[14];
System.out.println("The temperatures in the last two weeks...: ");
for(int i = 0; i < nums.length; i++) {
nums[i] = (int)(Math.random() * 11) + 50;
System.out.print(nums[i] + " ");
}
System.out.println("These 5 were below freezing...:");
}
}
An ArrayList or more generally a List is nothing more than a class that implements the List interface to facilitate manipulating collections of data.
In the case of ArrayList it uses a regular array (e.g. Object[]) to store the data while providing various methods to navigate and manipulate the list. Some specific differences from the users point of view between an ArrayList and an array are.
ArrayLists grow dynamically and do not need to be pre-allocated.
You can delete (remove) an element anywhere from an ArrayList.
You can see if the ArrayList contains a specific element.
You can easily sort an ArrayList
many other examples also exist.
None of the above capabilities are free. They are simply methods implemented in a class, acting as a front-end to an array to make writing code easier.
int [] array = new int[10];
// fill the array with ints
List<Integer> list = toList(array);
public List<Integer> toList(int[] a) {
// do something with a
// like print them out.
List<Integer> list = new ArrayList<>();
for (int i : a) {
list.add(i);
}
return list;
}

Trouble trying to invert an array list

I'm trying to invert an arrayList of votes in order to yield preference (i.e. a vote of 2,4,1,3, after inverted is 3,1,4,2. the indexed preference is 3). I believe this can be done with Collections but the list is of difference type (type Vote). Just need some guidance on how i could sort this preference order when i cant use Collections methods on Vote.
public Vote invertVote() {
VoteList invVote = (VoteList) ((Vote) vote).copyVote();
Iterator<Integer> iter = invVote.iterator();
while(iter.hasNext()){
iter.next();
Collections.reverse(invVote);
}
return invVote;
}
Note Vote is a collection of integers representing a single vote. VoteList implements Vote. copyVote() is used to create a deep copy of the vote in order to not alter it and return a new Vote object. Still stuck the error during Collections.reverse(invVote)
Yes this can be done using collection you just need to call the method Collections.reverse...
public static void reverse(List<?> list)
Reverses the order of the elements in the specified list.
This method
runs in linear time.
Example:
public static void main(String[] args) {
Random rnd = new Random();
List<Integer> myInteger = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
myInteger.add(rnd.nextInt(10));
}
// the list
System.out.println(myInteger);
// the list sorted
Collections.sort(myInteger);
System.out.println(myInteger);
// the list inverted
Collections.reverse(myInteger);
System.out.println(myInteger);
}
in your case use the class Votes instead of integer and make the class to implement the comparable interface where you define the sorting logic....
You can use Collections.reverse(list); check documentation.

Using List, how would I change this code as using List

So I have this code at the bottom, and I have to Instantiate myArray to a new array. Copy all data from int[] data to myArray. Set numMoves equal to 0. data Array holding the values input from the user. So this code I have here is done by just using int and just = signs and new, But now I need to change this Using "List" and I do not know what list is and how to use it. So what I need help on is What is List on java and how would I do this using List. Thanks, and i prefer telling me how it works thank you!
public class Deletions
{
private int[] myArray;
private int numMoves;
public Deletions(int[] data)
{
myArray = new int [data.length] ;
for(int n = 0; n < data.length; n++)
{
myArray[n] = data[n];
}
numMoves = 0;
}
At first, the original array copy method can be written like this.
int[] myArray = new int[data.length];
System.arraycopy(data, 0, myArray, 0, data.length);
and then, the solution will be
public List<Integer> copyToList(int[] data){
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < data.length; i++) {
list.add(data[i]);
}
return list;
}
or
public List<Integer> copyFromToList(List<Integer> data){
return new ArrayList<Integer>(data);
}
List is an ordered collection also known as Sequence. With ordered, it means that one can retrieve elements in the same Sequence as one has inserted the element into the List. Another important thing, List is interface not a concrete implementation. For concrete implementation, look at LinkedList/ArrayList etc.
To achieve the same result, I would write something like this:-
new ArrayList<>(Arrays.asList(data));
A list is any class whose instances can contain an ordered sequence of objects.
In Java, you most likely want to use ArrayList<E>, which is the generic list. Generic means that you can put whatever type of object in the list, as long as you specify that type (or one of its base types) in place of the E. An ArrayList<E> has methods such as add, get, and set.
For example:
ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(1337);
myList.add(42);
Look at the ArrayList<E> documentation for more information on what methods are available to you.
public class Deletions
{
private ArrayList<Integer> myArray;
private int numMoves;
public Deletions(int[] data)
{
myArray = new ArrayList<Integer>();
for(int n = 0; n < data.length; n++)
{
myArray.add(data[n]);
}
numMoves = 0;
}
}
http://docs.oracle.com/javase/tutorial/collections/implementations/list.html

Java - Reading from an ArrayList from another class

We've not covered ArrayLists only Arrays and 2D arrays. What I need to do is be able to read from an ArrayList from another class. The main aim is to read from them in a for loop and use the values stored in them to display items. However, I have made this quick program to test it out and keep getting this error
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at Main.Main(Main.java:14)
Here is my code
import java.util.ArrayList;
public class Main
{
public static void Main()
{
System.out.println("Test");
ArrayList <Objects> xcoords = new ArrayList<Objects>();
for( int x = 1 ; x < xcoords.size() ; x++ )
{
System.out.println(xcoords.get(x));
}
}
}
And then the class where the ArrayList is
import java.util.ArrayList;
public class Objects
{
public void xco()
{
ArrayList xcoords = new ArrayList();
//X coords
//Destroyable
xcoords.add(5);
xcoords.add(25);
xcoords.add(5);
xcoords.add(5);
xcoords.add(25);
xcoords.add(5);
//Static Walls
xcoords.add(600);
xcoords.add(400);
xcoords.add(600);
}
}
If someone can point me in the correct direction it would be so valuable. I've tried to debug however I can get anything helpful.
Thanks in advance.
Strictly speaking, the exception is due to indexing location 1 of an ArrayList with 0 elements. Notice where you start you for loop index variable x. But consider this line:
ArrayList <Objects> xcoords = new ArrayList<Objects>();
xcoords points to a new, empty ArrayList, not the one you created in class Objects. To get that ArrayList, change the method xco like
public ArrayList<Integer> xco() { // make sure to parameterize the ArrayList
ArrayList<Integer> xcoords = new ArrayList<Integer>();
// .. add all the elements ..
return xcoords;
}
then, in your main method
public static void main(String [] args) { // add correct arguments
//..
ArrayList <Integer> xcoords = (new Objects()).xco();
for( int x = 0 ; x < xcoords.size() ; x++ ) { // start from index 0
System.out.println(xcoords.get(x));
}
}
Here you're simply creating two completely unrelated lists. Either have the array list be a property of the Objects class and retrieve it through an instance method, or return it from an instance or static method, or make the property static. IMO the first two are preferable in most situations.
public class Objects {
public static List<Integer> getXcoords() {
List<Integer> xcoords = new ArrayList<Integer>();
// Your same code, but adding:
return xoords;
}
}
Then to use it:
import java.util.ArrayList;
public class Main {
// Note the lower-case "main" here. You want that.
public static void main() {
List<Integer> xcoords = Objects.getXcoords();
// etc.
Also, your List should be of Integer, not of Objects, which would create a collection holding instances of Objects. You may want to take a step back and relate lists to arrays in a better way--you wouldn't create an array of Objects, would you? No, you'd have an array of int or Integer.
Also, there's Arrays.asList.
You have an IndexOutOfBoundsException which means that you are trying to access an element in an array which is not existing.
But in your code posted here you are not accessing an array at all (your for loop will not execute once because the list is empty), which means that your exception is thrown somewhere else.
But also your code doesn't make any sense. I refactored it for you while staying as close to your code as possible, so you can see how it could work:
public static void main(String[] args){
Objects myObjects = new Objects();
ArrayList<Integer> listFromMyObjects = myObjects.getList();
for( int x = 0 ; x < listFromMyObjects.size() ; x++ )
{
System.out.println(listFromMyObjects.get(x));
}
}
public class Objects
{
private ArrayList<Integer> myList;
public Objects(){
myList = new ArrayList<Integer>();
myList.add(5);
myList.add(25);
myList.add(5);
myList.add(5);
myList.add(25);
myList.add(5);
myList.add(600);
myList.add(400);
myList.add(600);
}
public ArrayList<Integer> getList(){
return myList;
}
}

Categories

Resources