Difference between vector and ArrayList

Sometimes Vector is better; sometimes ArrayList is better; sometimes you don’t want to use either. I hope you weren’t looking for an easy answer because the answer depends upon what you are doing. There are four factors to consider:

  • API
  • Synchronization
  • Data growth
  • Usage patterns

Let’s explore each in turn.

API

In The Java Programming Language (Addison-Wesley, June 2000) Ken Arnold, James Gosling, and David Holmes describe the Vector as an analog to the ArrayList. So, from an API perspective, the two classes are very similar. However, there are still some major differences between the two classes.

Synchronization

Vectors are synchronized. Any method that touches the Vector‘s contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don’t need a thread-safe collection, use the ArrayList. Why pay the price of synchronization unnecessarily?

Data growth

Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It’s always best to set the object’s initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don’t know how much data you’ll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.

Usage patterns

Both the ArrayList and Vector are good for retrieving elements from a specific position in the container or for adding and removing elements from the end of the container. All of these operations can be performed in constant time — O(1). However, adding and removing elements from any other position proves more expensive — linear to be exact: O(n-i), where n is the number of elements and i is the index of the element added or removed. These operations are more expensive because you have to shift all elements at index i and higher over by one element. So what does this all mean?

It means that if you want to index elements or add and remove elements at the end of the array, use either a Vector or an ArrayList. If you want to do anything else to the contents, go find yourself another container class. For example, the LinkedList can add or remove an element at any position in constant time — O(1). However, indexing an element is a bit slower — O(i) where i is the index of the element. Traversing an ArrayList is also easier since you can simply use an index instead of having to create an iterator. The LinkedList also creates an internal object for each element inserted. So you have to be aware of the extra garbage being created.

www.pdf24.org    Send article as PDF   

How to get input from user in java

This program tells you how to get input from user in a java program. We are using Scanner class to get input from user. This program firstly asks the user to enter a string and then the string is printed, then an integer and entered integer is also printed and finally a float and it is also printed ion the screen. Scanner class is present in java.util package so we import this package in our program. We first create an object of Scanner class and then we use the methods of Scanner class. Consider the statement

 Scanner a  = new Scanner(System.in);

here Scanner is the class name, a is the name of object, new keyword is used to allocate the memory and System.in is the input stream. Following methods of Scanner class are used in the program below :-

1) nextInt to input an integer

2) nextFloat to input a float

3) nextLine to input a string

import java.util.*;

class GetInputFromUser
{
   public static void main(String args[])
   {
      int a;
      float b;
      String s;

      Scanner in = new Scanner(System.in);

      System.out.println("Enter a string");
      s = in.nextLine();
      System.out.println("You entered string "+s);

      System.out.println("Enter an integer");
      a = in.nextInt();
      System.out.println("You entered integer "+a);

      System.out.println("Enter a float");
      b = in.nextFloat();
      System.out.println("You entered float "+b);   
   }
}

 

www.pdf24.org    Send article as PDF   

Difference between throw and throws-Example

Like playing catch with a ball, programming involves trowing and catching exceptions. An exception is normally some problem that needs to be “fixed” by the programmer. But this means that we need to do more work. So here throwing comes in. If you do some logical test and you find that something funny is happening then you can “throw” an Exception instance. For example:

Code:
int a = 1, b = 0;
if (b != 0){
    // cool!
    int c = a / b;
} else {
    // Darn it.
    throw new Exception("Can't devide by zero!");
}

To catch it you use an try-catch block. Look at this method:

Code:
public static void go(){
    try{
        int a = 1, b = 0;
        if (b != 0){
            // cool!
            int c = a / b;
        } else {
            // Darn it.
            throw new Exception("Can't devide by zero!");
        }
    } catch (Exception e) {
        // Gotcha ha!
        System.out.println(e.getMessage());
    }
}

This means that you need to catch and handle the exception. Exceptions are not fun to work with, so you can pass it on the the user of your methods. Although, this is not very nice, but it can speed up your developing time. To “pass on” exceptions to the user of your method, you use the throws keyword:

Code:
public static void go() throws Exception{
    int a = 1, b = 0;
    if (b != 0){
        // cool!
        int c = a / b;
    } else {
        // Darn it.
        throw new Exception("Can't devide by zero!");
    }
}

The problem is that the user of this method must now worry about this:

Code:
try{
    go();
} catch (Exception e) {
    // Gotcha ha!
    System.out.println(e.getMessage());
}

It is possible to keep throwing an Exception, but it is not a very good way to program. The best way to handle exceptions, is as early as possible!

www.pdf24.org    Send article as PDF   

Creating User defined Exception

Though Java provides an extensive set of in-built exceptions, there are cases in which we may need to define our own exceptions in order to handle the various application specific errors that we might encounter.

While defining an user defined exception, we need to take care of the following aspects:

  • The user defined exception class should extend from Exception class.
  • The toString() method should be overridden in the user defined exception class in order to display meaningful information about the exception.

Let us see a simple example to learn how to define and make use of user defined exceptions.

NegativeAgeException.java

 public class NegativeAgeException extends Exception { private int age;  public NegativeAgeException(int age){  this.age = age; } public String toString(){ return "Age cannot be negative" + " " +age ;  } }

CustomExceptionTest.java

 public class CustomExceptionTest {  public static void main(String[] args) throws Exception{ int age = getAge(); if (age < 0){ throw new NegativeAgeException(age); }else{ System.out.println("Age entered is " + age); } }  static int getAge(){ return -10; } }

In the CustomExceptionTest class, the age is expected to be a positive number. It would throw the user defined exception NegativeAgeException if the age is assigned a negative number.

At runtime, we get the following exception since the age is a negative number.

Exception in thread "main" Age cannot be negative -10 at tips.basics.exception.CustomExceptionTest.main(CustomExceptionTest.java:10)

www.pdf24.org    Send article as PDF   

Difference between checked and unchecked exception:

A checked exception is any subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.

Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream’s read() method

Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked.

With an unchecked exception, however, the compiler doesn’t force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String’s charAt() method.

Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be, as they tend to be unrecoverable.

 

www.pdf24.org    Send article as PDF   

OSPF – Route Table Lookups

When an OSPF router examines the destination address of a packet, it takes the following steps to select the best route:

The lookup procedure described here adheres to RFC 2328. The earlier OSPF RFCs specify creating a set of matching routes first, then choosing the preferred path type, and choosing the longest match last.

1. Select the route or routes with the most specific match to the destination address. For example, if there are route entries for 172.16.64.0/18, 172.16.64.0/24, and 172.16.64.192/27 and the destination address is 172.16.64.205, the last entry will be chosen. The most specific match should
always be the longest match—the route with the longest address mask. The entries may be host, subnet, network, supernet, or default addresses. If no match can be found, an ICMP Destination Unreachable message will be sent to the source address and the packet will be dropped.
2. Prune the set of selected entries by eliminating less-preferred path types. Path types are prioritized in the following order, with 1 being the most-preferred and 4 being the least-preferred:
1. Intra-area paths
2. Inter-area paths
3. E1 external paths
4. E2 external paths

www.pdf24.org    Send article as PDF   

OSPF – Router Types

Internal Routers are routers whose interfaces all belong to the same area. These routers have a single link  state database.

Area Border Routers (ABRs) connect one or more areas to the backbone and act as a gateway for interarea traffic. An ABR always has at least one interface that belongs to the backbone, and must maintain a separate link state database for each of its connected areas. For this reason, ABRs often have more memory and perhaps more powerful processors than internal routers. An ABR will summarize the topological information of its attached areas into the backbone, which will then propagate the summary information to the other areas.

Backbone Routers are routers with at least one interface attached to the backbone. An Internal Router whose interfaces all belong to area 0 is also a Backbone Router.

Autonomous System Boundary Routers (ASBRs) are gateways for external traffic, injecting routes into the OSPF domain that were learned (redistributed) from some other protocol, such as the BGP and EIGRP processes. An ASBR can be located anywhere within the OSPF autonomous
system; it may be an Internal, Backbone , or ABR.

 

www.pdf24.org    Send article as PDF   

OSPF – Areas

Why Areas ?

OSPF, with its multiple databases and complex algorithms, can put greater demands on the memory and processors of a router than other routing protocols. As an internetwork grows, these demands can become significant or even crippling. And although flooding is more efficient than the periodic, full-table updates of RIP and IGRP, it can still place an unacceptable burden on the data links of a large internetwork.

OSPF uses areas to reduce these adverse effects. In the context of OSPF, an area is a logical grouping of  OSPF routers and links that effectively divide an OSPF domain into sub-domains. Routers within an area will have no detailed knowledge of the topology outside of their area.

  • A router must share an identical link state database only with the other routers in its area, not with the entire internetwork. The reduced size of the database reduces the impact on a router’s memory.
  • The smaller link state databases mean fewer LSAs to process and therefore less impact on the
    CPU.
  • Because the link state database must be maintained only within an area, most flooding is also
    limited to the area.

Three types of traffic may be defined in relation to areas:

  • Intra-area traffic consists of packets that are passed between routers within a single area.
  • Inter-area traffic consists of packets that are passed between routers in different areas.
  • External traffic consists of packets that are passed between a router within the OSPF domain and a
    router within another autonomous system.

Backbone Area :  Area ID 0 (or 0.0.0.0) is reserved for the backbone. The backbone is responsible for summarizing the
topographies of each area to every other area. For this reason, all inter-area traffic must pass through the backbone; non-backbone areas cannot exchange packets directly.

Stub Area

A stub area is an area into which AS External LSAs are not flooded. And if type 5 LSAs are not known inside an area, type 4 LSAs are unnecessary; these LSAs are also blocked. ABRs at the edge of a stub area will use Network Summary LSAs to advertise a single default route (destination 0.0.0.0) into the area. Any destination that the Internal Routers cannot match to an intra- or inter-area route will match the default route. Because the default route is carried in type 3 LSAs, it will not be advertised outside of the area.

Restrictions on stub areas
1. As in any area, all routers in a stub area must have identical link state databases. To ensure this condition, all stub routers will set a flag (the E-bit) in their Hello packets to zero; they will not accept any Hello from a router in which the E-bit is set to one. As a result, adjacencies will not be established with any router that is not configured as a stub router.
2. Virtual links cannot be configured within, or transit, a stub area.
3. No router within a stub area can be an ASBR. This restriction is intuitively understandable because ASBRs produce type 5 LSAs and type 5 LSAs cannot exist within a stub area.
4. A stub area may have more than one ABR, but because of the default route, the Internal Routers cannot determine which router is the optimal gateway to the ASBR.
Totally Stubby Areas

If memory is saved by blocking the propagation of type 5 and type 4 LSAs into an area, wouldn’t more memory be saved by blocking type 3 LSAs? In addressing this question, Cisco carries the concept of stub areas to its logical conclusion with a scheme known as totally stubby areas.
Totally stubby areas use a default route to reach not only destinations external to the autonomous system but also all destinations external to the area. The ABR of a totally stubby area will block not only AS External LSAs but also all Summary LSAs—with the exception of a single type 3 LSA to advertise the default route.

Not-So-Stubby Areas
A router with a few stub networks must be attached to the OSPF internetwork via one of the area 2 routers. The router supports only RIP, so the area 2 router will run RIP and redistribute the networks into OSPF. Unfortunately, this configuration makes the area 2 router an ASBR, and therefore area 2 can no longer be a stub area.

The RIP speaker does not need to learn routes from OSPF—a default route pointing to the area 2 router is all it needs. But all OSPF routers must know about the networks attached to the RIP router to route packets to them.

Not-so-stubby areas(NSSAs)[17] allow external routes to be advertised into the OSPF autonomous system while retaining the characteristics of a stub area to the rest of the autonomous system. To do this, the ASBR in an NSSA will originate type 7 LSAs to advertise the external destinations. These NSSA External LSAs are flooded throughout the NSSA but are blocked at the ABR.

The NSSA External LSA has a flag in its header known as the P-bit. The NSSA ASBR has the option of setting or clearing the P-bit. If the NSSA’s ABR receives a type 7 LSA with the P-bit set to one, it will translate the type 7 LSA into a type 5 LSA and flood it throughout the other areas. If the
P-bit is set to zero, no translation will take place and the destination in the type 7 LSA will not be advertised outside of the NSSA.

www.pdf24.org    Send article as PDF   

OSPF – LSA Types

 

  • LSA 1 (Router LSA)

Generated by all routers in an area to describe their directly attached links (Intra-area routes). These do not leave the area.

  • LSA 2 (Network LSA)

Generated by the DR of a broadcast or Nonbroadcast segment to describe the neighbors connected to the segment. These do not leave the area.

  • LSA 3 (Summary LSA)

Generated by the ABR to describe a route to neighbors outside the area. (Inter-area routes)

  • LSA 4 (Summary LSA)

Generated by the ABR to describe a route to an ASBR to neighbors outside the area.

  • LSA 5 (External LSA)

Generated by ASBR to describe routes redistributed into the area. These routes appear as E1 or E2 in the routing table. E2 (default) uses a static cost throughout the OSPF domain as it only takes the cost into account that is reported at redistribution. E1 uses a cumulative cost of the cost reported into the OSPF domain at redistribution plus the local cost to the ASBR.

  • LSA 6 (Multicast LSA)

Not supported on Cisco routers.

  • LSA 7 (NSSA External LSA)

Generated by an ASBR inside a NSSA to describe routes redistributed into the NSSA. LSA 7 is translated into LSA 5 as it leaves the NSSA. These routes appear as N1 or N2 in the ip routing table inside the NSSA. Much like LSA 5, N2 is a static cost while N1 is a cumulative cost that includes the cost upto the ASBR.

A good (and free) document for OSPF is the Cisco´s OSPF Design Guide, which can be found at:

http://www.cisco.com/en/US/tech/tk365/technologies_white_paper09186a0080094e9e.shtml

www.pdf24.org    Send article as PDF   

OSPF – Sequence Numbers, Checksum and Aging

Reliable Flooding: Sequencing, Checksums, and Aging
Each LSA contains three values that are used to ensure that the most recent copy of the LSA exists in
every database. These values are sequence number, checksum, and age.
OSPF uses a linear sequence number space and 32-bit signed sequence numbers ranging from InitialSequenceNumber (0x80000001) to
MaxSequenceNumber (0x7fffffff). When a router originates an LSA, the router sets the LSA’s sequence
number to InitialSequenceNumber. Each time the router produces a new instance of the LSA, the router
increments the sequence number by one.

Sequence number
If the present sequence number is MaxSequenceNumber and a new instance of the LSA must be created,
the router must first flush the old LSA from all databases. This is done by setting the age of the existing
LSA to MaxAge and reflooding it over all adjacencies. As soon as all adjacent neighbors have acknowledged the prematurely aged LSA, the new instance of the LSA with a sequence number of InitialSequenceNumber may be flooded.

Checksum

The checksum is a 16-bit integer calculated using a Fletcher algorithm. The checksum is calculated over
the entire LSA with the exception of the Age field (which changes as the LSA passes from node to node
and would therefore require recalculation of the checksum at each node). The checksum of each LSA is
also verified every five minutes as it resides in the link state database, to ensure that it has not been
corrupted in the database.

Aging

The age is an unsigned 16-bit integer that indicates the age of the LSA in seconds. The range is 0 to 3600
(1 hour, known as MaxAge). When a router originates an LSA, the router sets the age to 0. As the flooded
LSA transits a router, the age is incremented by a number of seconds specified by InfTransDelay. Cisco
routers have a default InfTransDelay of 1 second, which can be changed with the command ip ospf
transmit-delay. The age is also incremented as it resides in the database.

MaxAge
When an LSA reaches MaxAge, the LSA is reflooded and then flushed from the database. When a router
needs to flush an LSA from all databases, it prematurely sets the age to MaxAge and refloods it. Only the
router that originated the LSA can prematurely age it.

www.pdf24.org    Send article as PDF