The document discusses Java generics including:
- Creating generic classes using bounded types and wildcards to ensure type safety
- Defining generic methods and interfaces
- The benefits of generics like type safety, eliminating casting, and compile-time type checking
- Examples of generic classes holding different data types and comparing averages generically
CyberLab Training Division :
The .NET Framework is Microsoft's Managed Code programming model for building applications on Windows clients, servers, and mobile or embedded devices. Microsoft's .NET Framework is a software technology that is available with several Microsoft Windows operating systems. In the following sections describes , the basics of Microsoft .Net Frame work Technology and its related programming models.
What is Microsoft .Net Framework
what are the functions of microsoft .net framework?
Common Language Runtime in .Net Framework
How to Common Language Runtime
What is .Net Framework Class Library
What is Common Language Specification
What is Common Type System
What is Microsoft Intermediate Language
What is Portable Executable (PE) File Format
What is Microsoft Just In Time Compiler
How to Managed Code - Microsoft .Net Framework
What is .Net Framework Metadata
what is .Net Framework Assembly
What is Assembly Manifest
What is Global Assembly Cache
What is a .Net Satellite Assembly?
What are the contents of an Assembly?
How to Private Assembly and Shared Assembly
What is Microsoft .Net Strong Name
What is .Net Namespaces
What is Application Domain
What is Code Access Security
What is Garbage Collection
.Net Threads
For More Details.
Visit: http://www.cyberlabzone.com
Create a menu-driven program that will accept a collection of non-ne.pdfrajeshjangid1865
Create a menu-driven program that will accept a collection of non-negative integers from the
keyboard, calculate the mean and median values and display those values on the screen. Your
menu should have 6 options: 1. Add a number to the array 2. Display the mean 3. Display the
median 4. Print the array to the screen 5. Print the array in reverse order 6. Quit
Program particulars: Use an array of type int to store the integers entered by the user. There
must be error checking on the input integer. If it is negative, the program will print an error
message and re-prompt. This process will continue until a non-negative integer is entered. You
must use a try-catch structure to trap both types of input errors (like letters where numbers
should go) and range errors (like -1). You must write your own selectionSort utility method to
sort your array. Place the method in an external file named SortSearchUtil.java. There must be
error checking on the menu choice entered. If the user enters a choice not on the menu, the
program will print an error message, re-display the menu and re-prompt. This process will
continue until a valid option value is entered. Your solution must be modular. The design of your
methods is up to you, but the rules of “highly cohesive” and “loosely coupled” must be followed.
Your program should be well-documented. Explain what you’re doing in your code. Be sure to
include the usual name and assignment notes. Note your program will have to sort your array
before you can find the median. Include your SortSearchUtil.java file which will contain your
sort method.
This is what my project looks like already: Please fix it thanks. The SortSearchUtil will also be
included.
import java.util.Scanner;
public class ArraySorting
{
public static void main(String[] args)
{
int option;
int integer = 0;
int optionOne;
int optionTwo;
int optionThree;
int optionFour;
int optionFive;
int[] numbers = new int[5];
Scanner kb = new Scanner(System.in);
System.out.println(\"Please enter a non-negative integer: \");
integer = kb.nextInt();
while((integer < 0))
{
System.out.println(\"I am sorry that is not a non-negative integer.\");
System.out.println(\"\");
System.out.println(\"Please enter a non-negative integer: \");
integer = kb.nextInt();
}
option = displayMenu(kb);
while (option != 6)
{
switch (option)
{
case 1:
optionOne(numbers);
System.out.println(\"\");
break;
case 2:
optionTwo(numbers);
System.out.println(\"\");
case 3:
//optionThree();
System.out.println(\"\");
break;
case 4:
//optionFour();
System.out.println(\"\");
break;
case 5:
//optionFive();
System.out.println(\"\");
break;
}
option = displayMenu(kb);
}
if (option == 6)
{
System.out.println();
System.out.println(\"Thank you. Have a nice day.\");
}
}
private static int displayMenu(Scanner kb)
{
int option = 0;
while (option != 1 && option != 2 && option != 3 && option != 4 && option !=5 && option
!=6)
{
System.out.println(\"\\t\\t1. Add a number to the array\ \\t\\t2. Display the mean\ \\t\.
CyberLab Training Division :
The .NET Framework is Microsoft's Managed Code programming model for building applications on Windows clients, servers, and mobile or embedded devices. Microsoft's .NET Framework is a software technology that is available with several Microsoft Windows operating systems. In the following sections describes , the basics of Microsoft .Net Frame work Technology and its related programming models.
What is Microsoft .Net Framework
what are the functions of microsoft .net framework?
Common Language Runtime in .Net Framework
How to Common Language Runtime
What is .Net Framework Class Library
What is Common Language Specification
What is Common Type System
What is Microsoft Intermediate Language
What is Portable Executable (PE) File Format
What is Microsoft Just In Time Compiler
How to Managed Code - Microsoft .Net Framework
What is .Net Framework Metadata
what is .Net Framework Assembly
What is Assembly Manifest
What is Global Assembly Cache
What is a .Net Satellite Assembly?
What are the contents of an Assembly?
How to Private Assembly and Shared Assembly
What is Microsoft .Net Strong Name
What is .Net Namespaces
What is Application Domain
What is Code Access Security
What is Garbage Collection
.Net Threads
For More Details.
Visit: http://www.cyberlabzone.com
Create a menu-driven program that will accept a collection of non-ne.pdfrajeshjangid1865
Create a menu-driven program that will accept a collection of non-negative integers from the
keyboard, calculate the mean and median values and display those values on the screen. Your
menu should have 6 options: 1. Add a number to the array 2. Display the mean 3. Display the
median 4. Print the array to the screen 5. Print the array in reverse order 6. Quit
Program particulars: Use an array of type int to store the integers entered by the user. There
must be error checking on the input integer. If it is negative, the program will print an error
message and re-prompt. This process will continue until a non-negative integer is entered. You
must use a try-catch structure to trap both types of input errors (like letters where numbers
should go) and range errors (like -1). You must write your own selectionSort utility method to
sort your array. Place the method in an external file named SortSearchUtil.java. There must be
error checking on the menu choice entered. If the user enters a choice not on the menu, the
program will print an error message, re-display the menu and re-prompt. This process will
continue until a valid option value is entered. Your solution must be modular. The design of your
methods is up to you, but the rules of “highly cohesive” and “loosely coupled” must be followed.
Your program should be well-documented. Explain what you’re doing in your code. Be sure to
include the usual name and assignment notes. Note your program will have to sort your array
before you can find the median. Include your SortSearchUtil.java file which will contain your
sort method.
This is what my project looks like already: Please fix it thanks. The SortSearchUtil will also be
included.
import java.util.Scanner;
public class ArraySorting
{
public static void main(String[] args)
{
int option;
int integer = 0;
int optionOne;
int optionTwo;
int optionThree;
int optionFour;
int optionFive;
int[] numbers = new int[5];
Scanner kb = new Scanner(System.in);
System.out.println(\"Please enter a non-negative integer: \");
integer = kb.nextInt();
while((integer < 0))
{
System.out.println(\"I am sorry that is not a non-negative integer.\");
System.out.println(\"\");
System.out.println(\"Please enter a non-negative integer: \");
integer = kb.nextInt();
}
option = displayMenu(kb);
while (option != 6)
{
switch (option)
{
case 1:
optionOne(numbers);
System.out.println(\"\");
break;
case 2:
optionTwo(numbers);
System.out.println(\"\");
case 3:
//optionThree();
System.out.println(\"\");
break;
case 4:
//optionFour();
System.out.println(\"\");
break;
case 5:
//optionFive();
System.out.println(\"\");
break;
}
option = displayMenu(kb);
}
if (option == 6)
{
System.out.println();
System.out.println(\"Thank you. Have a nice day.\");
}
}
private static int displayMenu(Scanner kb)
{
int option = 0;
while (option != 1 && option != 2 && option != 3 && option != 4 && option !=5 && option
!=6)
{
System.out.println(\"\\t\\t1. Add a number to the array\ \\t\\t2. Display the mean\ \\t\.
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfFlorence Consulting
Quattordicesimo Meetup di Milano, tenutosi a Milano il 23 Maggio 2024 dalle ore 17:00 alle ore 18:30 in presenza e da remoto.
Abbiamo parlato di come Axpo Italia S.p.A. ha ridotto il technical debt migrando le proprie APIs da Mule 3.9 a Mule 4.4 passando anche da on-premises a CloudHub 1.0.
This 7-second Brain Wave Ritual Attracts Money To You.!nirahealhty
Discover the power of a simple 7-second brain wave ritual that can attract wealth and abundance into your life. By tapping into specific brain frequencies, this technique helps you manifest financial success effortlessly. Ready to transform your financial future? Try this powerful ritual and start attracting money today!
1.Wireless Communication System_Wireless communication is a broad term that i...JeyaPerumal1
Wireless communication involves the transmission of information over a distance without the help of wires, cables or any other forms of electrical conductors.
Wireless communication is a broad term that incorporates all procedures and forms of connecting and communicating between two or more devices using a wireless signal through wireless communication technologies and devices.
Features of Wireless Communication
The evolution of wireless technology has brought many advancements with its effective features.
The transmitted distance can be anywhere between a few meters (for example, a television's remote control) and thousands of kilometers (for example, radio communication).
Wireless communication can be used for cellular telephony, wireless access to the internet, wireless home networking, and so on.
Italy Agriculture Equipment Market Outlook to 2027harveenkaur52
Agriculture and Animal Care
Ken Research has an expertise in Agriculture and Animal Care sector and offer vast collection of information related to all major aspects such as Agriculture equipment, Crop Protection, Seed, Agriculture Chemical, Fertilizers, Protected Cultivators, Palm Oil, Hybrid Seed, Animal Feed additives and many more.
Our continuous study and findings in agriculture sector provide better insights to companies dealing with related product and services, government and agriculture associations, researchers and students to well understand the present and expected scenario.
Our Animal care category provides solutions on Animal Healthcare and related products and services, including, animal feed additives, vaccination
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC
Ellisha Heppner, Grant Management Lead, presented an update on APNIC Foundation to the PNG DNS Forum held from 6 to 10 May, 2024 in Port Moresby, Papua New Guinea.
1. Creating a custom generic class
Overview of generic programming,
Creating generic classes using Object class and by not using
Object class,
Creating generic methods,
Creating generic interfaces,
Using bounded types and WildCard
Using the type inference diamond to create an object
2. Overview of generic programming
The Java Generics programming is introduced in J2SE
5 to deal with type-safe objects.
Before generics, we can store any type of objects in
collection i.e. non-generic.
Now generics, forces the java programmer to store
specific type of objects.
3. In the simplest definition, generic programming is a
style of computer programming in which algorithms
are written in terms of to-be-specified-later types that
are then instantiated when needed for specific types
provided as parameters.
4. Advantage of Java Generics
There are mainly 3 advantages of generics.
They are as follows:
1) Type-safety :
1) We can hold only a single type of objects in generics.
2) It doesn’t allow to store other objects.
2) Type casting is not required:
1) There is no need to typecast the object.
Before Generics, we need to type cast.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0); //typecasting
After Generics, we don't need to typecast the object.
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
5. Advantage of Java Generics cont…
3) Compile-Time Checking:
1) It is checked at compile time so problem will not occur
at runtime.
2) The good programming strategy says it is far better to
handle the problem at compile time than runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32); //Compile Time Error
6. Example
class Gen<T>{
T ob;
Gen(T o){
ob = o;
}
T getob(){
return ob;
}
void showType(){
System.out.println("Type of T is " +ob.getClass().getName());
}
}
7. Example cont…
class GenDemo {
public static void main(String args[]){
Gen<Integer> iOb;
iOb = new Gen<Integer>(88);
iOb.showType();
int v = iOb.getob();
System.out.println("value: " + v);
Gen<String> strOb;
strOb = new Gen<String>("Generics Test");
strOb.showType();
String str = strOb.getob();
System.out.println("value: " + str);
}
}
8. Generics Work Only with Objects
When declaring an instance of a generic type, the type
argument passed to the type parameter must be a class type.
Gen<int> strOb = new Gen<int>(53);
// Error, can't use primitive type
A reference of one specific version of a generic type is not type
compatible with another version of the same generic type.
iOb = strOb; // Wrong!
9. Example using Object class
class NonGen {
Object ob;
NonGen(Object o) {
ob = o;
}
Object getob() {
return ob;
}
void showType() {
System.out.println("Type of ob is"+ob.getClass().getName());
}
}
10. Example using Object class cont…
class NonGenDemo {
public static void main(String args[]) {
NonGen iOb;
iOb = new NonGen(88);
iOb.showType();
int v = (Integer) iOb.getob();
System.out.println("value: " + v);
System.out.println();
NonGen strOb = new NonGen("Non-Generics Test");
strOb.showType();
String str = (String) strOb.getob();
System.out.println("value: " + str);
iOb = strOb;
v = (Integer) iOb.getob(); // run-time error!
}
}
11. Generic Class with
Multiple Type Parameters
class TwoGen<T, V> {
T ob1;
V ob2;
TwoGen(T o1, V o2) {
ob1 = o1;
ob2 = o2;
}
void showTypes() {
System.out.println("Type of T is " +ob1.getClass().getName());
System.out.println("Type of V is " +ob2.getClass().getName());
}
T getob1() {
return ob1;
}
V getob2() {
return ob2;
}
}
12. Generic Class with
Multiple Type Parameters cont…
class SimpGen {
public static void main(String args[]) {
TwoGen<Integer, String> t =
new TwoGen<Integer, String>(123, "Testing Two Parameter");
t.showTypes();
int v = t.getob1();
System.out.println("value: " + v);
String str = t.getob2();
System.out.println("value: " + str);
}
}
13. General Form of Generic Class
The generics syntax for declaring a generic class:
class class-name<type-param-list>
{ // ... }
The syntax for declaring a reference to a generic class:
class-name<type-arg-list> var-name =
new class-name<type-arg-list>(cons-arg-list);
14. Problem
Create a generic class that contains a method that returns
the average of an array of numbers of any type, including
integers, floats, and doubles.
15. Possible Solution
class Stats<T> {
T[] nums;
Stats(T[] o) {
nums = o;
}
double average() {
double sum = 0.0;
for(int i=0; i < nums.length; i++)
sum += nums[i].doubleValue(); // Error!!!
return sum / nums.length;
}
}
16. Why Error?
The compiler has no way to know that you are intending to
create Stats objects using only numeric types.
When we try to compile Stats, an error is reported that
indicates that the doubleValue( ) method is unknown.
We need some way to tell the compiler that we intend to pass
only numeric types to T.
17. Bounded Types
Used to limit the types that can be passed to a type parameter.
When specifying a type parameter, we can create an upper bound
that declares the super-class from which all type arguments must be
derived.
<T extends superclass>
A bound can include both a class type and one or more interfaces.
class Gen<T extends MyClass & MyInterface>
Any type argument passed to T must be a subclass of MyClass and
implement MyInterface.[TestAverageModified.java[Demo Program]]
18. Solution with No Error:
class Stats<T extends Number > {
T[] nums;
Stats(T[] o) {
nums = o;
}
double average() {
double sum = 0.0;
for(int i=0; i < nums.length; i++)
sum += nums[i].doubleValue(); // No Error!!!
return sum / nums.length;
}
}
19. Solution with No Error: cont…
class BoundsDemo {
public static void main(String args[]) {
Integer inums[] = { 1, 2, 3, 4, 5 };
Stats<Integer> iob = new Stats<Integer>(inums);
double v = iob.average();
System.out.println("iob average is " + v);
Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Stats<Double> dob = new Stats<Double>(dnums);
double w = dob.average();
System.out.println("dob average is " + w);
}
}
20. Problem
Create a generic class that contains a method sameAvg()
that determines if two Stats objects contain arrays that
yield the same average, no matter what type of numeric
data each object holds.
For example, if one object contains the double values 1.0,
2.0, and 3.0, and the other object contains the integer
values 2, 1, and 3, then the averages will be the same.
21. Possible Solution
Integer inums[] = { 1, 2, 3, 4 };
Double dnums[] = { 1.1, 2.2, 3.3, 4.4 };
Stats<Integer> iob = new Stats<Integer>(inums);
Stats<Double> dob = new Stats<Double>(dnums);
if(iob.sameAvg(dob))
System.out.println("Averages are the same.");
else
System.out.println("Averages differ.");
boolean sameAvg(Stats<T> ob)
{
if(average() == ob.average())
return true;
return false;
}
22. Why Error?
It will work only with the objects of same type.
if the invoking object is of type Stats<Integer>, then the
parameter ob must also be of type Stats<Integer>.
23. WildCard Argument
The wildcard simply matches the validity of object.
The wildcard argument is specified by the ?, and it represents an unknown
type.
boolean sameAvg(Stats<?> ob)
{
if(average() == ob.average())
return true;
return false;
}
Important: It is important to understand that the wildcard does not affect
what type of Stats objects can be created. This is governed by the extends
clause in the Stats declaration. The wildcard simply matches any valid Stats
object.
24. Generic methods
It is possible to declare a generic method that uses one or more
type parameters.
Methods inside a generic class are automatically generic
relative to the type parameters.
It is possible to create a generic method that is enclosed within
a non-generic class.
25. Generic methods cont…
The type parameters are declared before the return type of the
method.
Generic methods can be either static or non-static.
<type-param-list> ret-type method-name(param-list) {…}
Example:
public static <V, T extends V> boolean isIn(V value, T[] array)
This ability to enforce type safety is one of the most important
advantages of generic methods.
26. Example:
class GenMethDemo{
public static <V, T extends V> boolean isIn(V value, T[] array){
for(int i=0;i<array.length;i++){
if(value.equals(array[i]))
return true;
}
return false;
}
public static void main(String[] args){
Integer i[]={1,2,3,4,5,6};
System.out.println("2 is in Integer Array"+isIn(2,i));
String s[]={"one","two","three","four","five","six"};
System.out.println("one is in String Array"+isIn("one",s));
}
}
27. Generic Interfaces
Generic interfaces are specified just like generic classes.
Example:
interface MinMax<T extends Comparable<T>>
{ T min(); T max(); }
The implementing class must specify the same bound.
Once the bound has been established, it need not to be
specified again in the implements clause.
28. Generic Interfaces cont…
class MyClass<T extends Comparable<T>> implements MinMax <T extends
Comparable<T>> { //Wrong
In general, if a class implements a generic interface, then that class must also
be generic, at least to the extent that it takes a type parameter that is passed to
the interface. For example, the following attempt to declare MyClass is in
error:
class MyClass implements MinMax<T> { // Wrong!
Because MyClass does not declare a type parameter, there is no way to pass one
to MinMax. In this case, the identifier T is simply unknown, and the compiler
reports an error. Of course, if a class implements a specific type of generic
interface, such as shown here:
class MyClass implements MinMax<Integer> { // OK
29. Generic Interfaces cont…
interface MinMax<T extends Comparable<T>> {
T min();
T max();
}
class My<T extends Comparable<T>> implements
MinMax<T> {
…
}
30. Type inference diamond to
create an object
Without Type inference diamond to create an object:
Gen<Integer> iOb = new Gen<Integer>(88);
With Type inference diamond to create an object:
Gen<Integer> iOb = new Gen< >(88);
31. .doubleValue():method convert object into primitive
double (unboxing)
Boxing: conversion primitive data type into object.
Integer.parseInt(): Converion string into int
toString(): object to String
Before JDK5 : Comparable interface return
object.(need typecasting required,type safety less,
compile error checking)
After JDK5 version solve all the above problems and
we can make it genric.
32. T - Type
E - Element
K - Key
N - Number
V - Value