r/programminghelp • • Dec 16 '20

Java Searching for a single element of a multi element object in a Binary Search Tree

I'm having issues with one goal of my code. This project is supposed to be able to add, remove, search, and sort by major, objects in a BST.

My Student class is here: https://pastebin.com/TmJyvCYP

and My BST: https://pastebin.com/r1AEPzUk

the issue I'm running into is finding a way to search for a major and display all students in said major.

I've attempted to check to see if the ArrayList returned by the BST contained the string but when it runs it shows no indication of it working correctly as seen in case 3 of my main code: https://pastebin.com/c6xD0uqk

What would be the best way to go about this. It seemed like the professor was capable of finding this without using collections or iterating through the list. I know i should be using the arrayList, i'm just not sure HOW i need to implement it correctly.

(I've been working on a solution for this for hours and feel like it's going to be something very simple that I'm just missing)

5 Upvotes

2 comments sorted by

1

u/amoliski Dec 16 '20

Why not create a new getList function that includes a key and value parameter- ex:

students.getFilteredList("name", "bob") or setudents.getFilteredList("major", "MAT")

Then, as you iterate through your tree, only add the node to the result list if the chosen property has the specified value?

The other option is to get the full array list and then iterate through it and throw away items that don't match, but you mentioned wanting to avoid that option (plus it's less efficient).

1

u/Silicon_Folly Dec 16 '20

Yeah, it makes sense that that wouldn't work. First and foremost, you may want to consider renaming the second getList(...) method in BST class. The javadoc comment specifies "Returns an empty or complete tree based on the root node", and yet... the return type is void. I'd rename it to "populateListFromParentNode(...)" or "fillList(...)" or something more correct.

Your list that you are searching is a list of Student objects. Will a String of text describing the major ever be present in a list of objects?

So... you say want to use an ArrayList (one that you create every time getList() is called...) as input for searching by major. I'm a bit confused by your text here.

It seemed like the professor was capable of finding this without using collections or iterating through the list. I know i should be using the arrayList

The only way you are going to use the ArrayList is by iterating through the list and checking students.get(i).major. What's wrong with that searchByMajor() method you have commented out in StudentSearch? Maybe that you are missing curly brackets for the loop?