A Set of Sets with duplicate names? - java

I am in the process planning my next homework assignment, which is an anagram finder. I'm using java and would like to know if you can have a Set of Set's, where each Set have the same name currentSet (the names of each set are not unique or dynamically created? If this is too vague I can post my code to put it in context. Regards.

As #Hunter already mentioned, you can have Set of Sets. The code would be something like following:
import java.util.*;
public class TestingSets {
public static void main(String[] args) {
Set<Set<String>> mainSet = new HashSet<Set<String>>();
Set<String> s;
for (int i=0; i<10; i++){
s = new HashSet<String>();
s.add("Hi "+i);
mainSet.add(s);
}
}
}

Related

How to add another linked list objects

I a homework where I need to merge two linkedlist, "songs" list and "artists" linked list, it works on the first list the "song" list, but whenever i add another list it just wont work
as you can see here the public static void now has errors
package mergedlinkedlist;
import java.util.LinkedList;
public class Mergedlinkedlist {
public static void main(String[] args) {
LinkedList<String>song = new LinkedList<>();
song.add("imagine");
song.add("bohemian rhapsody");
song.add("highway to hell");
System.out.println(song);
}
public static void main(String[] args) {
LinkedList<String>artists = new LinkedList<>();
artists.add("john lennon");
artists.add("queen");
artists.add("ACDC");
System.out.println(artists);
}
Okey, as one comment has pointed out, no program can have 2 main methods. You cannot create another one.
I suggest to integrate the code from your second into your first. You can safely just add the contents together.
The task is to merge the lists. Do you need any more help with that?
Assuming the task says you know the size of the list you can just create a new list and use the same method you used above to add them to the list. If you do not, you will need to use a loop. It would look like this:
LinkedList<String>artistsAndSongs = new LinkedList<>();
if (artists.size() == songs.size()) {
for (int i = 0; i < artists.size(); i++) {
artistsAndSongs.add(artists.get(i));
artistsAndSongs.add(songs.get(i));
}
} else {
System.out.println("Not every artist is matched with a song!");
}
But you should read up on how linked lists work exactly in the documentation. This will not only improve your understanding of the class but also teach you how to quickly find solutions to your problem.
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html

Making all values in an array unique

Im making a small school project, keep in mind i'm a beginner. Im gonna make a small system that adds member numbers of members at a gym to an array. I need to make sure that people cant get the same member number, in other words make sure the same value doesnt appear on serveral index spots.
So far my method looks like this:
public void members(int mNr){
if(arraySize < memberNr.length){
throw new IllegalArgumentException("There are no more spots available");
}
if(memberNr.equals(mNr)){
throw new IllegalArgumentException("The member is already in the system");
}
else{
memberNr[count++] = mNr;
}
}
While having a contructor and some attributes like this:
int[] memberNr;
int arraySize;
int count;
public TrainingList(int arraySize){
this.arraySize = arraySize;
this.memberNr = new int[arraySize];
}
As you can see i tried using equals, which doesnt seem to work.. But honestly i have no idea how to make each value unique
I hope some of you can help me out
Thanks alot
You can use set in java
Set is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored.
mport java.util.*;
public class Set_example
{
public static void main(String[] args)
{
// Set deonstration using HashSet
Set<String> hash_Set = new HashSet<String>();
hash_Set.add("a");
hash_Set.add("b");
hash_Set.add("a");
hash_Set.add("c");
hash_Set.add("d");
System.out.print("Set output without the duplicates");
System.out.println(hash_Set);
// Set deonstration using TreeSet
System.out.print("Sorted Set after passing into TreeSet");
Set<String> tree_Set = new TreeSet<String>(hash_Set);
System.out.println(tree_Set);
}
}
public void members(int mNr){
if(arraySize < memberNr.length){
throw new IllegalArgumentException("There are no more spots available");
}
//You need to loop through your array and throw exception if the incoming value mNr already present
for(int i=0; i<memberNr.length; i++){
if(memberNr[i] == mNr){
throw new IllegalArgumentException("The member is already in the system");
}
}
//Otherwise just add it
memberNr[count++] = mNr;
}
I hope the comments added inline explains the code. Let me know how this goes.
Hey you can’t directly comparing arrays (collection of values with one integer value)
First iterate the element in membernr and check with the integer value

How good or bad is it to iterate over a hash-table after checking that it contains a value you want to remove?

I'm currently practicing Algorithm design on HackerRank.
This question pertains to the challenge found here:
https://www.hackerrank.com/challenges/ctci-ransom-note
I solved this problem fairly quickly. However, I ran into an issue that kind of bugs me. I can check for a value on my hash table by using the contains(value) function. However, I didn't see any way to retrieve the key/keys associated with it. In order to do this I was forced to iterate through the table until I found that value again.
While I see the usefulness of Hash Tables... I don't think I am going about solving the problem in an optimal way. I feel like it's a time waster to iterate through the table if I already know it contains the value I want to remove.
One idea I had was to make two tables and have them be the "mirrored" version of one another, as in the original map is using the numbers as keys and the copy or mirrored map uses the keys as the values. However, this seems impractical and I have a feeling that I'm just missing something essential in my knowledge of Hash functions or something.
One reason I'm thinking about this is that I recently made a program that uses a sqlight table to hold data. I only need one loop to search for and delete these values, which makes it more efficient doesn't it?
Could I please get an explanation of how to better achieve what my code below does?
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m = in .nextInt();
int n = in .nextInt();
String isTrue = "Yes";
Hashtable myTable = new Hashtable();
String magazine[] = new String[m];
for (int magazine_i = 0; magazine_i < m; magazine_i++) {
myTable.put(magazine_i, in .next());
}
Set < Integer > keySet = myTable.keySet();
for (int ransom_i = 0; ransom_i < n; ransom_i++) {
String temp = in .next();
//System.out.println("Line " + ransom_i);
if (!myTable.containsValue(temp)) {
isTrue = "No";
break;
} else {
for (int key: keySet) {
if (myTable.get(key).equals(temp)) {
myTable.remove(key);
//System.out.println("Found it");
break;
}
}
}
}
System.out.println(isTrue);
}
}
Here's an easy way to do it:
public class DenyReturn<K,T> extends Map<K,T>{
private Map m;
private List<T> dontreturn;
public DenyReturn(Map<K,T> m, List<T> dontreturn) {
this.m = m;
this.dontreturn = dontreturn;
}
public T get(Object key) {
T val = super.get(key);
if (dontreturn.contains(val)) return null;
return val;
}
//implement all other methods of Map by invoking the inner map methods
}

How to add to ArrayList in a For loop

I have a sequence of information being randomly generated. I would like to save that information in a variable of some kind so that it can be recalled elsewhere. i think I want to use an ArrayList, but I'm not sure how to add the information while inside a for loop (which is where it is being created). The code I have is as follows:
public static ArrayList<String> phoneList
public static void main(String[] args){
Random randomNumber = new Random();
int howMany = randomNumber.nextInt(11);;
String holding;
for (int i=0; i < howMany; i++){
int itemRandNum = randomNumber.nextInt(11);//for all Item Categories
int priceRandNum = randomNumber.nextInt(11);//Prices for all categories
holding = phones[itemRandNum]+" $"+ priceOfPhones[priceRandNum];
//System.out.println(holding);
phoneList.add("holding"); //here is where I would like to add the information
//contained in "holding" to the "phoneList" ArrayList.
}
System.out.println(phoneList);
}
I am getting a NullPointerException. If an ArrayList is not the best thing to use here, what would be?
Any help you can give is appreciated.
public static void String Main(String[] args) suggests this doesn't have much to do with Android.
First, instantiate the list (Outside your for loop):
phoneList = new ArrayList<>(howMany); //Adding "howMany" is optional. It just sets the List's initial size.
Then, add the values:
for (int i = 0; i < howMany; i++) {
//...
phoneList.add(holding);
//Don't place holding in quotation marks, else you'll just add "holding" for every entry!
}
You get a NullPointerException because ArrayList phoneList is null since you didn't initialize it. Therefore write
public static ArrayList<String> phoneList = new ArrayList<>();
As it is you are just declaring the class ArrayList not instantiating it. it is necessary for all the time you want to use a class to create an instance of the same class and thats simple, just do:
public static ArrayList phoneList = new ArrayList() (if you are running older versions of java), otherwise use public static ArrayList phoneList = new ArrayList<>().

How to add data to a Java List?

Please see the code below with which I am trying to create a List. Can anybody tell me why this code does not work?
class materialsStore {
List<String> lista = new ArrayList<String>();
public void add(String antikeimena){
lista.add(antikeimena);
}
public List<String> getList(){
return lista;
}
}
public class finalState {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
materialsStore materialObj = new materialsStore();
String stoixeia = input.nextLine();
for(int i=1;i<=10;i++){
materialObj.add(stoixeia);
}
materialObj.saying();
}
}
You want to add to the list 10 times. So change your code to add input.nextLine() into the loop.
String stoixeia=null;
for(int i=0;i<10;i++){
stoixeia = input.nextLine();
materialObj.add(stoixeia);
}
As a sidenote , classes in java by convention start with upper case so it should be MaterialsStore.
If you pepper your code with System.out.println() statements to see what values are at various points, it may tell you what your problems are. Alternately, you can learn to set breakpoints in your IDE for debugging.

Categories