Java Tuple-useful methods

Java Tuple-useful methods

Creating and Converting Tuples

with()- another way of instantiating a tuple. For example:

TupleType<Type1,Type2, etc> tupleName = TupleType.with( Type1Value, Type2Value, etc);

so its a simple way to create a tuple.

You can also do something similar with fromIterable(), fromCollection() and fromArray(), So it would be like this:

TupleType<Type1,Type2, etc> tupleName = TupleType.fromIterable(NameOfIterable);

TupleType<Type1,Type2, etc> tupleName = TupleType.fromArray(NameOfArray);

TupleType<Type1,Type2, etc> tupleName = TupleType.fromCollection(NameOfCollection);

or(only iterable has the ability to do this I believe)

TupleType<Type1,Type2, etc> tupleName = TupleType.fromIterable(NameOfIterable, index#);

The number of elements in the array, list or whatever else should be the same as the iterable (includes lists and arrays), unless you are using the second version of the iterable method(the with index#).

There are also conversion methods of a tuple to something else specifically toArray(),toList() and toString().Which work like:

Object[ ] arrayName = tupleName.toArray();

List<Object> listName = tupleName.toList();

String stringName= tupleName.toString();

I don’t believe you have to use object if all the values in the tuple are of the same datatype, but the type does have to match the type of all the elements in the tuple and Object is the only datatype that guarantees that it will.

Getting and setting Values

You can get a value in a tuple with getValue(), and getValueX(). An example of these are:

dataype variableName= TupleType.getValue#();

dataype variableName= TupleType.getValue(#);

These methods return a value so keep that in mind. The # stands for the index number of the element of the tuple you are getting.

You can set a value in a tuple with the setAtX(), which work similarly:

TupleType<Type1,Type2, etc> modTupleName = tupleName.setValue#(value);

Tuples are immutable so using these methods will return a new tuple so you should use it when modifying a tuple. Again # represents the index number and value represents what you are putting at that index number.

Adding and removing elements

So to add a element to a tuple you would use the add() or addAtX(). They are formatted like:

TupleType<Type1,Type2, etc> addTupleName = tupleName.addAt#(value);

TupleType<Type1,Type2, etc> addTupleName = tupleName.add(value);

So, add() will add the element to the end so it would be the last index. While addAtX() would add the element at the index of #. So, the index of what was added would be #. You can add multiple elements at the same time, but you have to make sure the TupleType matches the total amount of elements that will be in the Tuple. If you are adding a tuple to a tuple its the number of elements from tuple1 + number of elements of tuple2. Remember that these methods create a new tuple.

To remove a element use the removeFromX(). Which works like:

TupleType<Type1,Type2, etc> removeTupleName = tupleName.removeFrom#();

So, it basically deletes the element at index #. It has no parameters, and again it returns a tuple and the elements need to match what it will have when that element is removed.

Other

In order to figure out how many elements are in a tuple use getSize(). Which is formatted as :

int nameOfVar= tupleName.getSize();

Which has no parameters and returns a int that is the number of elements in the tuple.

To find the index of something use indexOf() or lastIndexOf(). Which is formatted like:

int nameOfVar= tupleName.indexOf(Value);

int nameOfVar= tupleName.lastIndexOf(Value);

So indexof() gives you the index of the first element that matches the value. lastIndexOf() finds the last element that matches the value.

There are also methods like contains(), containsAll(), equals(), which give a boolean and check to see if a tuple has something or if a tuple equals another tuple. I might make a separate post on these or add them here at a later time.

Java Tuple

Java Tuple

Tuples are a collection of objects of different types. The different types bit is what makes them different from arrays and lists. This would mean that you could have one object(with that tuple being that one object) contain all of someones identifying information, like age(int), gender(string), name(string), etc.

Ex:

Triplet<String, String, Integer> = new Triplet<String, String,Integer>(“Julia”, “female”, 20) ;

or in generalized form:

SpecificTupleType<ObjectType1,ObjectType2,etc> = new SpecificTupleType<ObjectType1,ObjectType2,etc>(Object1,Object2,etc);

That’s how you make a tuple by the way. So there are actually ten kinds of tuples, that vary bu how many objects you can have in a tuple, so for one object it would be a unit, two pair, three triplet, four quartet, etc. So the max number of objects you can have in a Tuple is 10. Also Java doesn’t have the JavaTuple data structure by default so you will need to download the JavaTuple library onto whatever platform you are using to make the program(EX.: Eclipse).

Some advantages to tuples are that they are immutable(which means you can’t change them after you have created them), they are type safe, they are serializable(which means that they can be put in the file system and can therefore be put into other applications) they can be used in iterations and they have things like toString() and equals() built into them.

Usefull Methods(will be updated with the rest of the information soon)

It’s possible I will also do one on the LabelValue and KeyValue classes.(There like another version of the pair tuple from my understanding).

Some sites to go to for more information are the tuple library which is already linked, geekforGeeks, tutorialspoints, and howtodoinjava.

objects vs classes

objects vs classes

The biggest thing to remember about objects and classes is that a object is a instance of a class. People commonly say that a class is a blueprint, and a object is a specific iteam made off of that blueprint. Another anology is that a class is a page in a coloring book, and a object is that coloring page fully colored, with the variables defined in the constructor being the colors.

An example of this is making a string:

string example = “object”:

So String is a class, and “example” is a object.

Some things to keep in mind is that their are static methods and variables and those belong to the class so if one object of that class changes a static variable, then that variable is changed for all the objects of the class during that runtime.

For example(in Java):

https://codehs.com/share/CountingObjects_sAXefQ

public class MyProgram
{
public static int numObj=0;
public int var=0;
public static int counto()
{
numObj++;
return numObj;
}
public int count()
{
var++;
return var;
}
public static void main(String[] args)
{
//static methods don’t have the object name in the call to the method because the object doesn’t //matter
MyProgram one = new MyProgram();
System.out.println(“these are the result of static variables”+ “\n”+counto());
// so numObj is 0 then 0+1=1
MyProgram two = new MyProgram();
System.out.println(counto());
//so numObj is 1 then 1+1=2

// non-static have the object name or this because it does matter
System.out.println(“These are the result of non-static” +”\n” +two.count()+ ” “+two.count() );
// so var =0 currently for object two ,so 0+1=1 then var now = 1 so 1+1=2
System.out.println(one.count()+ ” “+one.count() );
// so var =0 currently for object one so 0+1+=1, ten var now =1 so 1+1=2

}

}

Reserved words in java

Reserved words in java

Reserved words are keywords that the language uses to determine the properties of something. For example all of the datatypes, static , void, and abstract are reserved words. So while you can say put these words in a string, you can’t make the name of a variable, method, constructor or anything similar into one. They are also split into keywords and literals( like true and false). The list of them and a short description of what they do(from what I know) is below. I may have missed some since there is a lot and some I have never used. They are also all lowercase I am just to lazy to go and correct all of it.

Abstract- used in a method or class declaration and stops either from being used to make instances

Assert- used with assertion statements( whatever those are)

Boolean- a datatypes that uses true and false as values

Break- used to jump out of one set of parenthesis with if and switch statments

Byte- primitive datatypes can hold -128 to 127

Case- used in switch statments

Catch-used when looking for errors along with try

Char- datatypes where it’s a single letter that is given a number value

Class- used with declaring classes

Const- I don’t think it’s really used

Continue- used in a loop to jump to the next iteration of a loop

Default-declares default values and allows interface to provide the default of a method

Do- used in do while

Double- dataype to use for fractions and decimals Max and min is 17 followed by 307 zeros

Else- used in if else statments

Enum-dataype that can hold constants methods and more(I’ve never used this one either)

Extends- used when making a subclass

False-boolean dataype value

Final- used when making constants

Finally-follows a catch or try used to do things like ( I don’t really remember doing this)

Float- datatype for numbers the range is (2 to the-63) to ((2 to the 63)-1)

For- used in for loops

Goto- not used really

If- if statements

Implements- used when making a class inherit a interface

Import- used in import statement which are used to take in Java libraries

Instanceof -used to test if variable is of a specific type returns true or false( never had to use it)

Int- datatype USD with integer vslues

Interface- used when declaring interfaces

Long- another datatype got numbers min is 0 max is (2 to the 64) -1

Native- allows for Java to be called by other languages( I never had to do this)

New- used to initiate a new instance so like when declaring objects

Null- used to make sure there is actually a valid reference to a object

Package- used to group classes together

Private- used to make sure outside classes can’t access something( except for classes in the same package I think)

Protected- similar to private but allows for subclasses and package classes to use it ( I didn’t know this existed)

Public- the opposite of private

Return- used in methods to return a value to where the method was called

Short- datatype for numbers min -32,768 max 32,767

Static- used to make something apply to all instances

Strictfp- it supposedly restricts decimal calculations (what??????)

Super- used to call superclasses stuff

Switch- switch statement

Synchronized- prevents multiple pieces of code from accessing a certain piece of code at the same time( I never used it , but most of my programs it wouldn’t be a issue in the first place. My programs are too simple.)

this- used to reference current object

Throw- used to cause exeptions

Throws-used to list exeptions( I don’t do much with exeptions)

Transient- marks a variable to not be serialized, so the variable won’t be saved in a particular file ( umm I never used it but I googled it so …)

True- Boolean dataype value

Try- used with exeptions to make sure they don’t crash your program

Void- used to signify that there is no return in a method

Volatile- makes a variable stored in main memory ( so it’s ” thread-safe” apparently)

While – used on whole and do-while loops

objects

objects

A object is essentially the instance of a class. So alternatively a class is like the blueprint of a object.A object will have attributes and behaviors, like one would in real life.

A attribute would be like the color, length width and weight of iteam. This is typically represented through the parameters used when making a object( which are passes into the constructor and turned into fields/ global variables).

Behavior is the things the object can do. For example a tea kettle can boil water so a tea kettle object would have a method it could call to boil the water.

Creating a object:

ClassName objectName = new ClassName(<parameter>);

So when creating a object you need to declare what you will call it create the object with the new operator and call the constructer which initializes the object, similar to how you make a variable.

Calling a method:

Variablename = ObjectName.methodName(<parameter>);

Of course you can also declare a variable at the same time as calling the method and of the method is void you don’t set a variable to it.

Calling a field:

Most of the time you should have a get or set method but if you don’t . . .

objectName.varableName

Either in a system.print, parameter or setting a variable.

Interface

Interface

A interface is like a class where non of the methods have a body(called a abstract method) so a common analogy that is used for interfaces is that it’s like the blueprint of a class. Which basically means that tells what a class has to do but not how.So the main purpose of a interface is either to use polymorphism more effectively or to have interaction between to classes be based on the interfaces abstract methods which one of the classes implements since if the class implements the interface then it must define the methods given otherwise it becomes a abstract class and Java doesn’t support objects of abstract classes. (So by implementing the interface, the class is essentially promising that it will define the methods in the interface in that class or a subclass of that class)

A interface is made as shown below :

public interface interfaceName

{

returntype methodName(type parametername);

}

You can also make variable constants, but this isn’t recommended because the constants of different interfaces if given the same name and implemented by the same class could cause the program not to know which to use and cause a error.

In JDK8 and JDK9 there have been some updates to interface for more info on that you can look at the geek for geek article on interfaces( in case you didn’t realize it I’m not a professional so I do actually try to double check that my info is right before posting a article.)

Or you can wait till I add that information to here.

Some related topics are:

inheritance:

classes(not done yet):

Inheritance

Inheritance

Inheritance is where one class extends another or implements a interface, so in the case of extension it can call that classes methods, without making a object of the class. Other benefits include being able to use the superclass as a general class so you can have a parameter include the superclass and all subclasses of the superclass.

For example:

public class Balloon

public class RoundBalloon extends balloon

public class SquareBalloon extends balloon

public void draw(balloon k)

{

}

could take Balloon, SquareBalloon and/or RoundBalloon.

The drawback of inheritance in Java is that only one superclass can be extended so a class can’t inherit from multiple classes. However several interfaces can be implemented at the same time to (some extent) mimic multiple inheritance.

Related links are below:

Interfaces:

classes(not done yet):

Break vs continue

Break vs continue

Both of these reserved words are used in loops to end the current iteration of the loop often before getting to the end of the statements in the loop. They are also most often used inside of a if statement.

Break is used to end the loop before the loop would consider the condition false. So when the break statement is used it will end the loop and give control of the program to the statement right after the end of the loop. Break is also common to see inside of switch statements.

Continue is used to end the current iteration of the loop. So when it’s used it will disregard the rest of the loop that comes after it and go back to the conditional statement, and run the loop again as normal.

Ex:

for (int I =0; I<5; I ++)

{

if (j=3 && I=<2)

continue;

else if (j=3)// I >2

break;

else

j-1;

}

system.out.print(j);

So in this loop if j meets the conditions of the if statement then it will print out a 1. While if the conditions of the else if statement are met it will print out a 3. While if neither of them are met the answer it will print out will just be j(before the loop started)-5.

Sorting methods

Sorting methods

Sorting methods are ways to sort arrays in either ascending or descending order.WE sort arrays so they are easier to use. You  also use sorting methods to match two data sets, or presenting something in a orderly way.When sorting array we often use equals compareTo and/or compare methods. Also O( . . .) stands for time it takes for the program to sort in the worst case.

Merge-In merge sort you first make sure that there is more than one element if there is only one don’t do anything, if there are two swap them if you need to , if there are more than two split the array into to approximately equal halves, sort the first half of the array and the second half, and then merge the two halves back into one sorted array. Recursion is often used with this sorting method since it has a base case (when there is only one or two elements). It’s a O(n^2)

Quick-in quick sort you pick one element to be the pivot and then you sort around that pivot so that to the left are smaller elements and to the right are bigger elements. THen apply recursion to the right and left halves of the array.  It’s a O(n log n) algorithm.

Selection- In a selection sort you initialize a variable to the size of the array, find the largest element among the n elements, subtract one from n and repeat those steps except for initialization until n is less than or equal to 2.It’s a O(n^2) algorithm.

Insertion-In insertion sort you make n equal  to 1. Save the next element and find the place to insert it among the first n, shift elements as necessary and insert the saved one in the vacant slot, increment n by 1 and repeat steps except initialization until n is greater than array length. It’s a O(n^2) algorithm.

ArrayLists

ArrayLists

ArrayLists are similar to arrays but they will automatically increase the arrays capacity if you try to add a element to a already full arrayList. There are two important variables for arraylists: capacity and size. Capacity is the length of the current arraylist while size is the number of elements in the arraylist. A arrayList will always  hold a object. So if you want the arrayList to hold numbers you would use the Integer or Double object types. But you can add a primitive datatype to the list so long as that value is of the wrapper class that the arrayList has as its objectType. So like with ArrayList<Double> it will take 5.0 but it will not take 5 because 5 is a int not a double.

So you declare it in a field like:

private/public ArrayList<objectType> listName;

You declare it in  a method or constructor like:

ArrayList<objectType> listName = new ArrayList<objectType>();

You have to use the entire  ArrayList<objectType> whenever you are declaring variables, parameters, return values and when making one. Also the default capacity of a ArrayList is 10, which can be changed when declaring it by putting a whole number into the parenthesis.

The indices like Arrays start at zero and in order to get the size you use listName.size(), which as you can tell by the parenthesis is a method. A arraylist may use for each loops and when using methods that change the size of a array you have to be careful that you don’t accidentally skip any elements since if you delete a element the size will automatically decrement. Also a arrayList holds references to objects, and it can hold objects that are equal to each other and several references to the same object. Which means that the object can change after its been added to a Arraylist and the same object can belong to different arraylists.

A link to related topics is below:

For each loop;

Common Arraylist methods:

Arrays: