Instanceofkeyword Problem

In this Java program, we are dealing with a problem where we have an ArrayList that can contain instances of three different classes: Student, Rockstar, and Hacker. The task is to count the number of instances of each class present in the ArrayList.

Secure your next interview 🎯

CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷

Here is the Instanceofkeyword Problem HackerRank solution using CodeRankGPT:

The solution approach is to iterate over the ArrayList and use the 'instanceof' keyword to check the class of each element. If the element is an instance of the Student, Rockstar, or Hacker class, the respective counter is incremented. The count of each class is then returned as a string.


/**
 * 
 */
package com.javaaid.hackerrank.solutions.languages.java.oop;

import java.util.ArrayList;
import java.util.Scanner;

/**
 *
 */
class Student {
}

class Rockstar {
}

class Hacker {
}

public class JavaInstanceofkeyword {

	static String count(ArrayList mylist) {
		int a = 0, b = 0, c = 0;
		for (int i = 0; i < mylist.size(); i++) {
			Object element = mylist.get(i);
			if (element instanceof Student)
				a++;
			if (element instanceof Rockstar)
				b++;
			if (element instanceof Hacker)
				c++;
		}
		String ret = Integer.toString(a) + " " + Integer.toString(b) + " " + Integer.toString(c);
		return ret;
	}

	public static void main(String[] args) {
		ArrayList mylist = new ArrayList();
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		for (int i = 0; i < t; i++) {
			String s = sc.next();
			if (s.equals("Student"))
				mylist.add(new Student());
			if (s.equals("Rockstar"))
				mylist.add(new Rockstar());
			if (s.equals("Hacker"))
				mylist.add(new Hacker());
		}
		System.out.println(count(mylist));
		sc.close();
	}
}

If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.

AI is here now, and other candidates might be using it to get ahead and win the job. 🧐

Built on Unicorn Platform