Programming project, ADT Lists - java

We recently switched professors and this new professor was under the impression that we had a wealth of knowledge we do not possess.
We have a programming project due and I would just like some clarification, if possible.
(From exercise 4.4) Write a method void interchange (List l) which interchanges the current element in the list and the one following it. (First make it work in the normal case; then, if you still have time, make sure it handles special cases, such as: the list is empty; the list has only one element; current is at the end of the list
(From exercise 4.6) Write a method void reverse (List l) which reversed the order of items stored in the list. Again, make sure it works for any special cases you can think of.
(From exercise 4.7) Write a method List mergeLists (List l1, List l2)which takes two sorted Lists as input, producing a new List containing all the elements of both lists, also sorted. The new list is the return value for the method.
So I created a list
ArrayList<String> numbers = new ArrayList<String>();
numbers.add("Zero");
numbers.add("One");
numbers.add("Two");
numbers.add("Three");
System.out.println (numbers);
And so I'm assuming that under this I'm to make these 3 new methods. I'm just having a hard time following his instructions. I'm not asking anyone to do my work for me, I would just like some clarification on exactly what he wants us to do, and I can subsequently attempt to do research.
Thank you in advance.

I think your professor is asking for something more abstract than what you did.
You are supposed to, first, define your own class representing a list element such as
class List {
int data;
List next;
}
Then you are given a list say List myList. It is supposed all elements are in there already.
Then you are supposed to write a function, say void reverse(List list) that, given that myList would reverse it in place etc, etc.
Exercies like this are in many books. Your professor wants to give you some abstract knowledge which is more valuable than some particular language syntax.

Related

If some function parameter recieves List<List<Integer>> nums , then the nums is instantiated by LinkedList or ArrayList?

Both LinkedList and ArrayList are built on the List interface, yet the LinkedList uses the traditional pointer technique to build a list, and ArrayList uses array to implement List functionality . So what can one claim before using the nums will it be using ArrayList or LinkedList behind the screen?
How I got this question?
public int[] smallestRange(List<List<Integer>> nums) {
}
}
Most of The Leetcode Java question has this format of the input. Without the prior knowledge of how the nums have been instantiated, how can someone use nums.get(i) function (list.get(i) is O(1) in ArrayList and O(n) in linkedList )
99% of the time, it'll be an ArrayList, and you want to use an ArrayList in your code. They use less memory, are faster, and code taking advantage of LinkedList can usually be rewritten to use two ArrayLists. The main downside is add() occasionally running in O(n) time.
how can someone use nums.get(i)
You don't. You take advantage of the list being Iterable and do things like for-each loops:
for (var i : list) {
...
}
this runs in O(n) time for both LinkedList and ArrayList.
Technically, there's an interface called RandomAccess you can check to see if get() is O(1). You probably don't want it, though. Use the iterator.
if (list instanceof RandomAccess) {
list.get(...);
}
You can't directly predicate that what is default implementation of the List Interface. Interface is just a specification and you have multiple implementations of List Interface like you have mentioned in the image.
Every implementation will just override the method that mentioned in the List interface but their logic will be different based on the data structure.
Now its totally depend upon you which implementation you want based on your requirement. Whether you have space constraint or time constraint. But both will have same method as they are specified in interface.
As per coding challenges platform I think they specify the code from where they have call this method. You can check there But if it is not specified then most probably they will choose ArrayList - for time constraint. And I think a user should not be worried about the implementation that the they chosen. As I told user should know what is his requirement and then only choose implementations.
It can be either of them:
List<List<Integer>> list1 = new ArrayList<>();
List<List<Integer>> list2 = new LinkedList<>();
int[] x = smallestRange(list1); //works
int[] y = smallestRange(list2); //also works
You need to make your code be able to cater to both types

TreeSet vs ArrayList and sort [duplicate]

I have implemented a graph.
I want to sort a given subset of vertices with respect to their degrees.
Therefore, I've written a custom comparator named DegreeComparator.
private class DegreeComparator implements Comparator<Integer>
{
#Override
public int compare(Integer arg0, Integer arg1)
{
if(adj[arg1].size() == adj[arg0].size()) return arg1 - arg0;
else return adj[arg1].size() - adj[arg0].size());
}
}
So, which one of the below is more efficient?
Using TreeSet
public Collection<Integer> sort(Collection<Integer> unsorted)
{
Set<Integer> sorted = new TreeSet<Integer>(new DegreeComparator());
sorted.addAll(unsorted);
return sorted;
}
Using ArrayList
Collections.sort(unsorted, new DegreeComparator());
Notice that the second approach is not a function, but a one-line code.
Intuitively, I'd rather choose the second one. But I'm not sure if it is more efficient.
Java API contains numerous Collection and Map implementations so it might be confusing to figure out which one to use. Here is a quick flowchart that might help with choosing from the most common implementations
A TreeSet is a Set. It removes duplicates (elements with the same degree). So both aren't equivalent.
Anyway, if what you want naturally is a sorted list, then sort the list. This will work whether the collection has duplicates or not, and even if it has the same complexity (O(n*log(n)) as populating a TreeSet, it is probably faster (because it just has to move elements in an array, instead of having to create lots of tree nodes).
If you only sort once, then the ArrayList is an obvious winner. The TreeSet is better if you add or remove items often as sorting a list again and again would be slow.
Note also that all tree structures need more memory and memory access indirection which makes them slower.
If case of medium sized lists, which change rather frequently by a single element, the fastest solution might be using ArrayList and inserting into the proper position (obviously assuming the arrays get sorted initially).
You'd need to determine the insert position via Arrays.binarySearch and insert or remove. Actually, I would't do it, unless the performance were really critical and a benchmark would show it helps. It gets slow when the list get really big and the gain is limited as Java uses TimSort, which is optimized for such a case.
As pointed in a comment, assuring that the Comparator returns different values is sometimes non-trivial. Fortunately, there's Guava's Ordering#arbitrary, which solves the problem if you don't need to be compatible with equals. In case you do, a similar method can be written (I'm sure I could find it somewhere if requested).

Storing 15,000 items in Java

I have a document with 15,000 items. Each item contains 6 variables (strings and integers). I have to copy all of these into some sort of two dimensional array, what the best way to do it?
Here are my ideas so far:
Make a GIANT 2D array or array list the same way you make any other array.
Pros: Simple Cons: Messy(would create a class just for this), huge amount of code, if I make a mistake it will be imposable to find where it is, all variables would have to be string even the ints which will make my job harder down the road
Make a new class with a super that takes in all the variables I need.
Create each item as a new instance of this class.
Add all of the instances to a 2D array or array list.
Pros: Simple, less messy, easier to find a mistake, not all the variables need to be strings which makes it much easier later when I don't have to convert string to int, a little less typing for me Cons: Slower? Will instances make my array compile slower? And will they make the over all array slow when I'm searching to items in it?
These ideas don't seem all to great :( and before I start the three week, five hour a day process of adding these items I would like to find the best way so I won't have to do it again... Suggestions on my current ideas or any new ideas?
Data example:
0: 100, west, sports, 10.89, MA, united
*not actual data
Your second options seems to be good. You can create a class containing all the items and create an array of that class.
You may use the following:
1. Read the document using buffered reader, so that memory issues will not occur.
2. Create a class containing your items.
3. Create a List of type you need and store the elements into it.
Let me know in case you face further problems.
If you already have the document with the 15000 * 6 items, in my experience you would be better served writing a program to use regex and parse it and have the output be the contents of the java array in the format you want. With such a parsing program in place, it will then also be very easy for you to change the format of the 15000 lines if you want to generate it differently.
As to the final format, I would have an ArrayList of your bean. By you text thus far, you don't necessarily need a super that takes in the variables, unless you need to have subtypes that are differentiated.
You'll probably run out of static space in a single class. So what I do is break up a big class like that into a file with a bunch of inner nested classes that each have a 64K (or less) part of the data as static final arrays, and then I merge them together in the main class in that file.
I have this in a class of many names to fix:
class FixName{
static String[][] testStrings;
static int add(String[][] aTestStrings, int lastIndex){
for(int i=0; i<aTestStrings.length; ++i) {
testStrings[++lastIndex]=aTestStrings[i];
}
return lastIndex;
}
static {
testStrings = new String[
FixName1.testStrings.length
+FixName2.testStrings.length
+FixName3.testStrings.length
+FixName4.testStrings.length
/**/ ][];
int lastIndex=-1;
lastIndex=add(FixName1.testStrings,lastIndex);
lastIndex=add(FixName2.testStrings,lastIndex);
lastIndex=add(FixName3.testStrings,lastIndex);
lastIndex=add(FixName4.testStrings,lastIndex);
/**/ }
}
class FixName1 {
static String[][] testStrings = {
{"key1","name1","other1"},
{"key2","name2","other2"},
//...
{"keyN","nameN","otherN"}
};
}
Create a wrapper (Item) if you have not already(as your question does not state it clearly).
If the size of the elements is fixed ie 1500 use array other wise use LinkedList(write your own linked list or use Collection).
If there are others operations that you need to support on this collection of items, may be further inserts, search( in particular) use balanced binary search tree.
With the understanding of the question i would say linked list is better option.
If the items have a unique property (name or id or row number or any other unique identifier) I recommend using a HashMap with a wrapper around the item. If you are going to do any kind of lookup on your data (find item with id x and do operation y) this is the fastest option and is also very clean, it just requires a wrapper and you can use a datastructure that is already implemented.
If you are not doing any lookups and need to process the items en masse in no specific order I would recommend an ArrayList, it is very optimized as it is the most commonly used collection in java. You would still need the wrapper to keep things clean and a list is far cleaner than an array at almost no extra cost.
Little point in making your own collection as your needs are not extremely specific, just use one that is already implemented and never worry about your code breaking, if it does it is oracles fault ;)

Is an ArrayList the same thing as a singly-linked list?

In Java, I have been asked to store integer values in a singly-linked list and then print the elements stored in the list. Here is what I came up with:
int max = 10;
List<Integer> list = new ArrayList<Integer>();
for (int num = 0; i < max; i++){
list.add(num);
}
System.out.print(list);
I was wondering, is ArrayList the same thing as a singly-linked list? I want to make sure that I'm answering the question correctly. Does this make sense? Thanks!
No - ArrayList is not a linked list at all - it's an array list. ArrayList stores its elements in an array, whereas linked lists store them in arbitrary memory by linking objects together.
LinkedList is a doubly-linked list, and I'm sure that there are various singly linked list implementations you could grab, but given that this is an assignment you'll either be marked down or fail outright if you try to hand in code using someone else's implementation.
Instead, find an article etc. which describes linked lists and try to implement one yourself.
Generally these are built in java by having a class SomeClass containing a forward link of type SomeClass and a value. You build the list by linking each SomeClass instance to the next through the forward link.
No ArrayList is definitely not the same as a singly linked list. In fact, it is not a linked list at all: it is a list that uses an array for its backing storage. This lets you access ArrayList in arbitrary order, as opposed to linked lists, that must be accessed sequentially.
Java library has a doubly-linked list, but no singly-linked one; you need to write it yourself.
There are several good implementations available on the internet; take a look at this answer on the codereview site to gain some ideas on how to implement a singly linked list of your own.
No, ArrayList is an implementation of the List interface that uses a backing array to store the data. It sounds like the assignment wants you to write your own singly-linked List implementation.
No, an ArrayList is backed by an array. Arrays utilize contiguous storage (that is, the start of the array + offset of size of whatever is stored in the array == next element). Java has a LinkedList class, however, this is a doubly linked list, meaning that it contains two references: one to the previous element, and one to the next element.
Java does not have a singly linked list as a built in data structure. Either the question is asking you write your own implementation of a singly linked list, or is incorrect when it says to use one.
The name "Array"List states that the underlying implementation uses "arrays" for management. Whenever we talk about "Linked"List we are actually thinking about "Noded" lists i.e. every element has got a pointer to the forward node (and previous node if doubly-linked list). At least that's what this DSA book (by Granville Barnett and Luca Del Tongo) is saying.
In commercial Life your Solution is Perfect, but unfortunately ist seems that you are requested to use a Single linkes List which in Std Java does Not exist.
(And would Not make much sense)
For Purpos of Training you have to Write your own List.

Printing out items in any Collection in reverse order?

I have the following problem in my Data Structures and Problem Solving using Java book:
Write a routine that uses the Collections API to print out the items in any Collection in reverse order. Do not use a ListIterator.
I'm not putting it up here because I want somebody to do my homework, I just can't seem to understand exactly what it is asking for me to code!
When it asks me to write a 'routine', is it looking for a single method? I don't really understand how I can make a single method work for all of the various types of Collections (linked list, queue, stack).
If anybody could guide me in the right direction, I would greatly appreciate it.
Regardless from the question not making much sense as half of the collections have no gstable ordering of have fixed-ordering (i.e. TreeSet or PriorityQueue), you can use the following statement for printing the contents of a collection in reverse-natural order:
List temp = new ArrayList(src);
Collections.reverse(temp);
System.out.println(temp);
I essence you create an array list as lists are the only structure that can be arbitrarily reordered. You pass the src collection to the constructor which initializes the list withj the contents of the src in the collection natural order. Then you pass the list to the Collections.reverse() method which reverses the list and finally you print it.
First, I believe it is asking you to write a method. Like:
void printReverseList(Collection col) {}
Then there are many ways to do this. For example, only using the Collection API, use the toArray method and use a for loop to print out all the items from the end. Make sense?
As for the various classes using the Collection interface, it will automatically work for all of those since they must implement the interface (provided they implement it in a sane way;).
Well you could have a routine that delegates to other routines based on the input type, however I'm not sure there is a generic enough collection type that can be encompassed into one argument. I guess you could just use method overloading (having multiple methods with the same name, but accept different args).
That could technically count as 1 routine (all have the same name).
I don't know much Java, but considering the "Collections API" i imagine all those objects implement an interface you could iterate through someway. i suppose they all could have an itemAtIndex( int index ) and length() or similar method you could use.
You might want to read this.
Isn't there a base Collection class?
Probably worth looking here as a starting point: Collections.

Categories