Printing Out a hashset to screen - java

I am attempting to print out a hashset taking in records from a database which are currently stored in two seperate ArrayLists. When I attempt to print out the HashSet the following error shows.
This is your HashSet[nyu.Sorting#378bf509, nyu.Sorting#7b23ec81, nyu.Sorting#15aeb7ab, nyu.Sorting#27d6c5e0, nyu.Sorting#7ef20235, nyu.Sorting#4f3f5b24, nyu.Sorting#6acbcfc0, nyu.Sorting#2d98a335, nyu.Sorting#5fd0d5ae, nyu.Sorting#16b98e56]
And this is my code:
public static HashSet<Sorting> t() {
Sorting s = new Sorting();
int TimeNeededOne = 75;
int TimeNeededTwo = 75;
int assignedTimeOne = 0;
int assignedTimeTwo = 0;
HashSet<Sorting> c = new HashSet<Sorting>();
for(int i=0; i<=i1.size()-1; i++)
{
if((assignedTimeOne < TimeNeededOne) && !(assignedTimeOne+ i1.get(i).getLengthMins() > offensiveTimeInMins) )
{
c.add(i1.get(i));
assignedTimeOne += i1.get(i).getLengthMins();
}
}
for(int i=0; i<=i2.size()-1; i++)
{
if((assignedTimeTwo < TimeNeededTwo) && !(assignedTimeTwo + i2.get(i).getLengthMins() > TimeNeededTwo) )
{
c.add(i2.get(i));
assignedTimeTwo += i2.get(i).getLengthMins();
}
}
System.out.println("Training programme :" + c.size());
System.out.println("This is your training programme" + c.toString());
return c;
}
The c.size is there to confirm that ten entries are made which is correct however the formatting of the records from the hashset obviously contains a problem. Any help with this issue would be greatly appreciated.
Thanks.

One way of doing this would be to override the toString() method of your Sorting class to print its contents:
public class Sorting {
...
#Override
public String toString() {
// Return a String that represents this object
return "...";
}
}

You need override toString() method in the Sorting class, for example:
class Sorting {
...
#Override
public String toString() {
// a string representation of Sorting object
}
}
java.util.Iterator runs through the whole collection and for each element invokes a toString() method. The data recorded in the java.lang.StringBuilder, which returns of its string representation at the end.

Related

Implementation of Radix sort in Java using Nodes instead of integers

I have a final project for my Data Structures class that I can't figure out how to do. I need to implement Radix sort and I understand the concept for the most part. But all the implementations I found online so far are using it strictly with integers and I need to use it with the other Type that I have created called Note which is a string with ID parameter.
Here is what I have so far but unfortunately it does not pass any JUnit test.
package edu.drew.note;
public class RadixSort implements SortInterface {
public static void Radix(Note[] note){
// Largest place for a 32-bit int is the 1 billion's place
for(int place=1; place <= 1000000000; place *= 10){
// Use counting sort at each digit's place
note = countingSort(note, place);
}
//return note;
}
private static Note[] countingSort(Note[] note, long place){ //Where the sorting actually happens
Note[] output = new Note[note.length]; //Creating a new note that would be our output.
int[] count = new int[10]; //Creating a counter
for(int i=0; i < note.length; i++){ //For loop that calculates
int digit = getDigit(note[i].getID(), place);
count[digit] += 1;
}
for(int i=1; i < count.length; i++){
count[i] += count[i-1];
}
for(int i = note.length-1; i >= 0; i--){
int digit = getDigit((note[i].getID()), place);
output[count[digit]-1] = note[i];
count[digit]--;
}
return output;
}
private static int getDigit(long value, long digitPlace){ //Takes value of Note[i] and i. Returns digit.
return (int) ((value/digitPlace ) % 10);
}
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
//Main Method
public static void main(String[] args) {
// make an array of notes
Note q = new Note(" ", " ");
Note n = new Note("CSCI 230 Project Plan",
"Each person will number their top 5 choices.\n" +
"By next week, Dr. Hill will assign which piece\n" +
"everyone will work on.\n");
n.tag("CSCI 230");
n.tag("final project");
Note[] Note = {q,n};
//print out not id's
System.out.println(Note + " Worked");
//call radix
Radix(Note);
System.out.println(Note);
//print out note_id's
}
}
Instead of
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
I should have used
public Note[] sort(Note[] s) { //
s = Radix(s);
return s;
}
and change the variable type of Radix from void to Note[].

Sorting objects in an ArrayList without using Collections.sort

I would like to use my own sorting method instead of Collections.sort so that I can tinker around with my program to understand other sorts, generics, and ArrayLists better.
I have an employee class that has an employee number member. I know how to make an ArrayList of Employee objects, but could you explain how I could print and sort them? I started off by sorting a regular array and wanted to do the same with an ArrayList of Employee objects (the employee number). I'm having trouble understanding how to print ArrayLists of objects and sorting them.
package dataStructures;
import java.util.ArrayList;
import java.util.Arrays;
public class SortPractice {
public static void main(String[] args) {
int[] nums = {5,4,3,2,1};
System.out.println(Arrays.toString(nums));
BubbleSort1(nums);
ArrayList<Employee> empList = new ArrayList<Employee>();
for (int i=0; i<10; i++) {
empList.add(new Employee(10-i));
}
BubbleSort(empList); //This method doesn't work. I need help here.
}
public static void BubbleSort (int[] A) { //I included this because I know it works.
int temp = 0;
int firstLoopCount = 0;
int SecLoopCount = 0;
for (int i=0; i< A.length-1; i++) {
firstLoopCount++;
System.out.println(Arrays.toString(A) + i + " << First Loop interation");
for (int j=0; j<A.length-1; j++) {
if (A[j] > A[j+1]) {
temp = A[j];
A[j] = A[j+1];
A[j+1] = temp;
}
SecLoopCount++;
System.out.println(Arrays.toString(A) + j + " << Second Loop Interation");
}
}
System.out.println((firstLoopCount+SecLoopCount));
}
public static void BubbleSort (ArrayList<Employee> empList) { //I tried to use the same
int temp = 0; //approach just with the List
int firstLoopCount = 0;
int SecLoopCount = 0;
for (int i=0; i<empList.size()-1; i++) {
firstLoopCount++;
System.out.println(Arrays.toString(empList) + i + " << First Loop interation");
for (int j=0; j<empList.size()-1; j++) {
if (empList.get(j) > empList.get(j+1)) { //I get errors here in Eclipse and
temp = A[j]; //up above when I use toString
A[j] = A[j+1];
A[j+1] = temp;
}
SecLoopCount++;
System.out.println(Arrays.toString(A) + j + " << Second Loop Interation");
}
}
System.out.println((firstLoopCount+SecLoopCount));
}
Here is the employee class. It has other getters and setters but I didn't include them.
package dataStructures;
public class Employee {
private int empNum;
private String firstName;
private String LastName;
private String email;
public Employee(int empNum) {
this.empNum = empNum;
}
public String toString(){
return " "+ empNum + ",";
}
public Employee() {
}
public int getEmpNum() {
return empNum;
}
public void setEmpNum(int empNum) {
this.empNum = empNum;
}
Accessing an array is different from accessing an ArrayList. This is because these two objects are fundamentally different.
Let's focus on this line of code:
System.out.println(Arrays.toString(empList) + i + " << First Loop interation");
You're going to want to bookmark the Java 7 API so that you can reference what it is these methods actually take as arguments. Believe me, it will save you lots of time in the long run.
Specifically, the code is invalid because toString does not accept a parameter of type ArrayList. You can just straight-up print an ArrayList, as it has a reasonable toString method, whereas an array doesn't (which is why you use Arrays#toString):
System.out.println(empList.toString() + i + " << First Loop interation");
Let's look at this if block next:
if (empList.get(j) > empList.get(j + 1)) { //I get errors here in Eclipse and
temp = A[j]; //up above when I use toString
A[j] = A[j + 1];
A[j + 1] = temp;
}
I'll be blunt, you're going to get errors in any reasonable IDE with that code. The reason: you index into arrays with brackets, but you use get for an ArrayList.
The first fix is that you can't compare those two instances with >. What you'd wind up doing instead is retrieving the field you want to compare it with instead.
if(empList.get(j).getEmpNum() > empList.get(j+1).getEmpNum()) {
// more code
}
Here's the relevant Javadoc for ArrayList. You're going to need it.
Let's focus on the inner part of the if. The operation you're doing there is called a swap. You're taking an element from one location and overwriting it with another. Since arrays don't shift elements down, you have to capture the original value before you overwrite it.
To put it in English:
Take original value
Place new value in original value's original array location
Place original value in new value's original array location
You shouldn't have to do that with an ArrayList, as it can add the element in a specific spot.
In English, it should be as simple as:
Insert new value in original value's spot
Delete new value's occurrence in the list
In Java, it might read like this:
if(empList.get(j).getEmpNum() > empList.get(j + 1).getEmpNum()) {
empList.add(j, empList.get(j + 1));
empList.remove(j + 1);
}
One problem I noticed is in this line -
empList.get(j) > empList.get(j+1)
You are comparing 2 objects, i.e. 2 employee objects, this is usually not used other than for primitive types (e.g. Integer).
What you probably want to compare is the employee IDs which I assume is in your Employee.java file (please post this file so we can take a look). Here's an example of what you could do for this line -
empList.get(j).getEmployeeId() > empList.get(j+1).getEmployeeId()
Edit: sorry read the question wrong, not using Collections.sort()
Here is an example. In this case, your class has to provide a method that overrides the compareTo method in the Comparable interface. The specification is that it should return an integer greater than 0 if the calling object is greater, or an integer less than 0 if the caller is less, return 0 otherwise.
public class Employee implements Comparable {
//Rest of your class code here
public void getID() {
//return some value associated with the ID
}
//override this method
public int compareTo(Employee other) {
//code to compare two Employees
// Maybe something like the following
if (this.getID() > other.getID()) {
return 1;
} else if (this.getID() < other.getID()) {
return -1;
} else {
return 0;
}
}
}
This is the final answer with the help of #Makoto
public static void BubbleSort (ArrayList<Employee> empList) {
for (int i=0; i<empList.size()-1; i++) {
for (int j=0; j<4; j++) {
if (empList.get(j).getEmpNum() > empList.get(j+1).getEmpNum()) {
empList.add(j, empList.get(j + 1)); //This line inserts the smaller value
empList.remove(j+2); //into the first index and pushes the
} //indices down 1. So I need to remove
//j+2 not j+1.
/*When I use the debugger to step into toString() it says source not found.
I don't get it but it works.*/
System.out.println(empList.toString() + j + " << Second Loop Interation");
}
System.out.println(empList.toString() + i + " << First Loop interation");
}
}

How to find index of STRING array in Java from a given value?

I wanted to know if there's a native method in array for Java to get the index of the table for a given value ?
Let's say my table contains these strings :
public static final String[] TYPES = {
"Sedan",
"Compact",
"Roadster",
"Minivan",
"SUV",
"Convertible",
"Cargo",
"Others"
};
Let's say the user has to enter the type of car and that then in the background the program takes that string and get's it's position in the array.
So if the person enters : Sedan
It should take the position 0 and store's it in the object of Cars created by my program ...
Type in:
Arrays.asList(TYPES).indexOf("Sedan");
String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
if (TYPES[i].equals(carName)) {
index = i;
break;
}
}
After this index is the array index of your car, or -1 if it doesn't exist.
for (int i = 0; i < Types.length; i++) {
if(TYPES[i].equals(userString)){
return i;
}
}
return -1;//not found
You can do this too:
return Arrays.asList(Types).indexOf(userSTring);
I had an array of all English words. My array has unique items. But using…
Arrays.asList(TYPES).indexOf(myString);
…always gave me indexOutOfBoundException.
So, I tried:
Arrays.asList(TYPES).lastIndexOf(myString);
And, it worked. If your arrays don't have same item twice, you can use:
Arrays.asList(TYPES).lastIndexOf(myString);
try this instead
org.apache.commons.lang.ArrayUtils.indexOf(array, value);
Use Arrays class to do this
Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");
No built-in method. But you can implement one easily:
public static int getIndexOf(String[] strings, String item) {
for (int i = 0; i < strings.length; i++) {
if (item.equals(strings[i])) return i;
}
return -1;
}
There is no native indexof method in java arrays.You will need to write your own method for this.
An easy way would be to iterate over the items in the array in a loop.
for (var i = 0; i < arrayLength; i++) {
// (string) Compare the given string with myArray[i]
// if it matches store/save i and exit the loop.
}
There would definitely be better ways but for small number of items this should be blazing fast. Btw this is javascript but same method should work in almost every programming language.
Try this Function :
public int indexOfArray(String input){
for(int i=0;i<TYPES,length();i++)
{
if(TYPES[i].equals(input))
{
return i ;
}
}
return -1 // if the text not found the function return -1
}
Testable mockable interafce
public interface IArrayUtility<T> {
int find(T[] list, T item);
}
implementation
public class ArrayUtility<T> implements IArrayUtility<T> {
#Override
public int find(T[] array, T search) {
if(array == null || array.length == 0 || search == null) {
return -1;
}
int position = 0;
for(T item : array) {
if(item.equals(search)) {
return position;
} else {
++position;
}
}
return -1;
}
}
Test
#Test
public void testArrayUtilityFindForExistentItemReturnsPosition() {
// Arrange
String search = "bus";
String[] array = {"car", search, "motorbike"};
// Act
int position = arrayUtility.find(array, search);
// Assert
Assert.assertEquals(position, 1);
}
Use this as a method with x being any number initially.
The string y being passed in by console and v is the array to search!
public static int getIndex(int x, String y, String[]v){
for(int m = 0; m < v.length; m++){
if (v[m].equalsIgnoreCase(y)){
x = m;
}
}
return x;
}
Refactoring the above methods and showing with the use:
private String[] languages = {"pt", "en", "es"};
private Integer indexOf(String[] arr, String str){
for (int i = 0; i < arr.length; i++)
if(arr[i].equals(str)) return i;
return -1;
}
indexOf(languages, "en")

Setting up the Structure of a Polynomial

I'm trying to evaluate the structure of a polynomial by simply listing the coefficients and displaying them with a variable with its respected power. I'm not evaluating, I'm just trying to get the equation out there.
public class TestPolynomialBackup{
public static void main(String[] args){
Polynomial p1 = new Polynomial(4);
System.out.println(p1);
}
public static class Polynomial
{
private int[] coef;
private int power=3;
public Polynomial(int a ){
coef = new int []{4,3,2,1};
}
public String toString() {
for(int i=0;i<coef.length-1;i++){
String s = coef[2] + "x^" + power;
return s;
}
}
}
}
Output: TestPolynomialBackup.java:38: error: missing return statement
}
I keep getting that error at the toString() method. All i'm trying to do is to make a for-loop that will go down the array of coefficents with some conditions that will determine if the character "x" (variable) will appear as well as the power.
You might wanna get more familiar with Java and think about what you want this method to do:
public String toString() {
for (int i = 0; i < coef.length - 1; i++) {
String s = coef[2] + "x^" + power;
return s;
}
}
This is propably what you want:
public String toString() {
StringBuilder s = new StringBuilder();
for (int i = 0; i < coef.length; i++) {
if (i != 0)
s.append(" + ");
s.append(coef[i]);
s.append("x^");
s.append(i);
}
return s.toString();
}
Changes:
put return outside of loop
accumulate result instead of somehow always creating a new string
actually use your index i inside of the loop
let the loop go from 0 to coef.length - 1
added " + " as a delimiter
You should add a return after your for loop.
The compiler can't compile because if your loop is not executed, your method would return nothing.
But you should review the way your loop is working, since you have a return in it, it is executed only once.

Java - Returning from a recursive function

I'm trying to return all possible permutations of values in a String array. I've come up with the following code making all possible permutations; it works fine.
private void combineArray(String sPrefix, String[] sInput, int iLength) {
if (iLength == sPrefix.length()) {
//This value should be returned and concatenated:
System.out.println(sPrefix);
} else {
for (int i=0; i<sInput.length; i++) {
combineArray(sPrefix.concat(sInput[i]), ArrayUtils.removeElement(sInput, sInput[i]), iLength);
}
}
}
If I put in {x, y ,z} it prints to the console:
xyz
xzy
yxz
yzx
zxy
zyx
My problem is that I can't find a way to return these values to the original calling function. So I'd like this function not to return 'void' but a 'String' containing the concatened values of sPrefix.
I've been struggling with this for a while now and I can't seem to see clearly anymore. :) Any help would be appreciated.
Rather than returning a list, I think it might work better to pass in a list as an argument, and populate it inside the method:
private void combineArray(List<String> lOut, String sPrefix, String[] sInput, int iLength) {
if (iLength == sPrefix.length()) {
//This value should be returned and concatenated:
System.out.println(sPrefix);
lOut.add(sPrefix);
} else {
for (int i=0; i<sInput.length; i++) {
combineArray(lOut, sPrefix.concat(sInput[i]), ArrayUtils.removeElement(sInput, sInput[i]), iLength);
}
}
}
You can then have a wrapper method that creates the new ArrayList<String>, passes it into the above method, and returns it.
You can have an ArrayList<String> and add all the strings to it.. And then you can return this ArrayList..
List<String> listString = new ArrayList<>();
private void combineArray(String sPrefix, String[] sInput, int iLength) {
if (iLength == sPrefix.length()) {
listString.add(sPrefix);
//This value should be returned and concatenated:
System.out.println(sPrefix);
} else {
for (int i=0; i<sInput.length; i++) {
combineArray(sPrefix.concat(sInput[i]), ArrayUtils.removeElement(sInput, sInput[i]), iLength);
}
}
return listString;
}
Keep appending to the same output.. Like this:
private String combineArray(String sPrefix, String[] sInput, int iLength, String output) {
if (iLength == sPrefix.length()) {
//This value should be returned and concatenated:
System.out.println(sPrefix);
output = output+"|+sPrefix;
return output;
} else {
for (int i=0; i<sInput.length; i++) {
output = combineArray(sPrefix.concat(sInput[i]), ArrayUtils.removeElement(sInput, sInput[i]), iLength, output);
}
}
}
You can also use a ListArray instead of a String, once the basic concept works..

Categories

Resources